Skip to content

Instantly share code, notes, and snippets.

@burnsie7
Last active April 8, 2020 13:47
Show Gist options
  • Save burnsie7/025b9fdbaac85025c260c126dde94493 to your computer and use it in GitHub Desktop.
Save burnsie7/025b9fdbaac85025c260c126dde94493 to your computer and use it in GitHub Desktop.
Native Tracing w/ NodeJS

Create service and add dependencies

serverless create --template hello-world
npm init
npm install dd-trace@dev
npm install serverless-plugin-datadog

Install Lambda Forwarder

https://github.com/DataDog/datadog-serverless-functions/tree/master/aws/logs_monitoring#installation

Modify serverless.yaml and add the following:

    layers:
      - arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Node12-x:21
    environmentVariables:
      # Optional for trace_id log injection
      DD_LOGS_INJECTION: true
    plugins:
      - serverless-plugin-datadog

serverless.yaml:

service: hello-world

# The `provider` block defines where your service will be deployed
provider:
  name: aws
  runtime: nodejs12.x
  profile: serverless
# The `functions` block defines what code to deploy
functions:
  helloworld:
    handler: handler.helloworld
    # The `events` block defines how to trigger the handler.helloWorld code
    events:
      - http:
          path: hello-world
          method: get
          cors: true
    layers:
      - arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Node12-x:21
    environmentVariables:
      # Optional for trace_id log injection
      DD_LOGS_INJECTION: true
    plugins:
      - serverless-plugin-datadog

Modify handler.js to include datadog lambda layer and tracer:

const { datadog } = require("datadog-lambda-js");
const tracer = require("dd-trace").init();

handler.js:

'use strict';

const { datadog } = require("datadog-lambda-js");
const tracer = require("dd-trace").init();

// This function will be wrapped in a span
const someFunction = tracer.wrap('some-function', () => {
    // An expensive calculation goes here
});

// This function will also be wrapped in a span
module.exports.helloworld = datadog((event, context, callback) => {
    someFunction();
    callback(null, {
        statusCode: 200,
        body: 'Hello from serverless!'
    });
});

Deploy

serverless deploy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment