How to use aws-xray-sdk-core - 10 common examples

To help you get started, we’ve selected a few aws-xray-sdk-core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github motdotla / node-lambda / test / handler / index.js View on Github external
exports.handler = (event, context, callback) => {
  // It changes to a boolean value with `!!`
  context.callbackWaitsForEmptyEventLoop =
    !!event.callbackWaitsForEmptyEventLoop

  if (event.asyncTest) {
    setTimeout(() => console.log('sleep 3500 msec'), 3500)
  }

  // https://docs.aws.amazon.com/xray/latest/devguide/scorekeep-lambda.html
  // For testing AWSXRay support
  AWSXRay.captureFunc('annotations', (subsegment) => {
    subsegment.addAnnotation('Name', 'name')
    subsegment.addAnnotation('UserID', 'piyo')
  })

  /* eslint-disable no-eval */
  eval(event.callbackCode)
}
github aws-samples / aws-xray-kubernetes-serverless / lambda / index.js View on Github external
var AWSXRay = require("aws-xray-sdk-core");
var logger = require('winston');
AWSXRay.setLogger(logger);
var AWS = AWSXRay.captureAWS(require('aws-sdk'));

var docClient = new AWS.DynamoDB.DocumentClient({
  apiVersion: '2012-08-10'
});

// Table name is configured as env var.
var table = process.env.TABLE_NAME;

exports.handler = (event, context, callback) => {

  console.log('Received event:', JSON.stringify(event, null, 2));

  var responseBody = {
      message: ""
  };
github alessandrobologna / serverless-tracking-pixel / handler.js View on Github external
'use strict';

const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
//const AWS = require('aws-sdk');
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');
const kinesis = new AWS.Kinesis();
const kms = new AWS.KMS();

// function to determine if the cookie exists and is valid
const verify = (cookie, secret) => {
	let segments = cookie.split('/');
	return segments.length === 2 && (crypto.createHmac('sha256', secret).update(segments[0]).digest('hex') === segments[1]);
}

let secret = undefined

const decrypt = () => {
	if (!secret) {
github UnaBiz / sigfox-gcloud / lib / aws.js View on Github external
return new Promise((resolve) => {
          //  Publish the message body as an AWS X-Ray annotation.
          //  This allows us to trace the message processing through AWS X-Ray.
          AWSXRay.captureAsyncFunc(topicName, (subsegment0) => {
            subsegment = subsegment0;
            try {
              const msg = JSON.parse(buffer.toString());
              const body = msg.body || msg;
              if (!body) {
                console.log('awsGetTopic', 'no_body');
                return resolve('no_body');
              }
              for (const key of Object.keys(body)) {
                //  Log only scalar values.
                const val = body[key];
                if (val === null || val === undefined) continue;
                if (typeof val === 'object') continue;
                subsegment.addAnnotation(key, val);
              }
            } catch (error) {
github allthings / serverless-boilerplates / typescript / src / handler.ts View on Github external
),
  },
  enableCompression: IS_PRODUCTION,
  headers: {
    'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
  },
}

/*
  Enable X-Ray in production
  See the results here:
  https://console.aws.amazon.com/xray/home#/service-map
*/
if (IS_PRODUCTION) {
  // tslint:disable:no-expression-statement no-var-requires
  AwsXray.captureHTTPsGlobal(require('http'))
  AwsXray.captureHTTPsGlobal(require('https'))
  // tslint:enable
}

// @TODO: remove type 'any'
export default handler(async (request: any, response: any) => {
  const SUPER_SECRET = await kmsDecrypt(process.env.SUPER_SECRET || '') // result gets cached :-)

  const { body } = request

  if (SUPER_SECRET !== process.env.SUPER_SECRET) {
    // The rules are only disabled because this is an example and
    // console.log-ing makes for a simple example. Don't copy me.
    // tslint:disable-next-line:no-expression-statement no-console
    console.log('SUPER_SECRET was decrypted.')
  }
github allthings / serverless-boilerplates / javascript-webhook-dynamodb / src / handler.js View on Github external
].join(' '),
    'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com', CDN_HOST_URL].join(' '),
  },
  enableCompression: IS_PRODUCTION,
  headers: {
    'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
  },
}

/*
  Enable X-Ray in production
  See the results here:
  https://console.aws.amazon.com/xray/home#/service-map
*/
if (IS_PRODUCTION) {
  AwsXray.captureHTTPsGlobal(require('http')) // eslint-disable-line global-require
  AwsXray.captureHTTPsGlobal(require('https')) // eslint-disable-line global-require
}

export default handler(async (request, response) => {
  const SUPER_SECRET = await kmsDecrypt(process.env.SUPER_SECRET || '') // result gets cached :-)
  const { body: webhookPayload } = request
  const { id } = webhookPayload

  if (SUPER_SECRET !== process.env.SUPER_SECRET) {
    console.log('SUPER_SECRET was decrypted.')
  }

  if (!id) {
    return response.json(
      { error: 'Missing required "id" field in JSON request body.', request: webhookPayload },
      400
github jaydp17 / series-notifier-serverless / src / process-query-function / index.ts View on Github external
import { env } from '../common/environment';
import * as InternalTypes from '../common/internal-message-types';
import { invokeMessengerReply } from '../common/lambda-utils';
import * as Subscription from '../models/subscription';
import * as ActionHelper from './action-helper';
import * as NextEpisodeController from './controllers/next-episode.controller';
import * as SearchController from './controllers/search.controller';
import * as TrendingController from './controllers/trending.controller';

const { ActionTypes, ReplyKind } = InternalTypes;

if (!process.env.IS_LOCAL) {
  // tslint:disable-next-line: no-console
  console.log('capturing outgoing http calls in X-Ray');
  // tslint:disable-next-line no-var-requires
  AWSXRay.captureHTTPsGlobal(require('http'));
}

export async function handler(
  action: InternalTypes.AnyAction,
  context: {},
  callback: LambdaCallback,
): Promise<void> {
  if (env !== 'test') {
    console.log('entry'); // tslint:disable-line:no-console
    prettyPrint(action);
  }

  const socialId = ActionHelper.getSocialId(action);

  // compute the reply
  let reply;
github jaydp17 / series-notifier-serverless / src / messenger-reply-function / index.ts View on Github external
import { LambdaCallback } from '../common/aws-lambda-types';
import { getError } from '../common/common-utils';
import { errorMessages } from '../common/constants';
import { env } from '../common/environment';
import * as InternalTypes from '../common/internal-message-types';
import * as MessengerTypes from '../common/messenger-types';
import * as MessengerAPI from '../common/messenger.api';
import { generateGenericTemplate } from './messenger.formatter';

const { ReplyKind } = InternalTypes;

if (!process.env.IS_LOCAL) {
  // tslint:disable-next-line: no-console
  console.log('capturing outgoing http calls in X-Ray');
  // tslint:disable-next-line no-var-requires
  AWSXRay.captureHTTPsGlobal(require('http'));
}

export async function handler(
  reply: InternalTypes.AnyReplyKind,
  context: {},
  callback: LambdaCallback,
): Promise<void> {
  if (env !== 'test') {
    console.log('input', JSON.stringify(reply)); // tslint:disable-line:no-console
  }

  if (isEmpty(reply.metaData)) {
    return callback(new Error('no metaData'));
  }
  const metaData = reply.metaData.fbMessenger;
  if (isEmpty(metaData)) {
github aws-samples / eb-java-scorekeep / _lambda / random-name / index.js View on Github external
var myFunction = function(event, context, callback) {
  var sns = new AWS.SNS();
  var chance = new Chance();
  var userid = event.userid;
  var name = chance.first();

  AWSXRay.captureFunc('annotations', function(subsegment){
    subsegment.addAnnotation('Name', name);
    subsegment.addAnnotation('UserID', event.userid);
  });

  // Notify
  var params = {
    Message: 'Created randon name "' + name + '"" for user "' + userid + '".',
    Subject: 'New user: ' + name,
    TopicArn: process.env.TOPIC_ARN
  };
  sns.publish(params, function(err, data) {
    if (err) {
      console.log(err, err.stack);
      callback(err);
    }
    else {
github aws-samples / aws-xray-kubernetes-serverless / lambda / index.js View on Github external
var AWSXRay = require("aws-xray-sdk-core");
var logger = require('winston');
AWSXRay.setLogger(logger);
var AWS = AWSXRay.captureAWS(require('aws-sdk'));

var docClient = new AWS.DynamoDB.DocumentClient({
  apiVersion: '2012-08-10'
});

// Table name is configured as env var.
var table = process.env.TABLE_NAME;

exports.handler = (event, context, callback) => {

  console.log('Received event:', JSON.stringify(event, null, 2));

  var responseBody = {
      message: ""
  };