Home

Awesome

⚑️ Serverless Sentry Plugin

serverless nodejs npm license dependencies prettier

About

This Serverless plugin simplifies the integration of Sentry with the popular Serverless Framework and AWS Lambda.

Currently, we support Lambda Runtimes for Node.js 12, 14, and 16 for AWS Lambda. Other platforms can be added by providing a respective integration library. Pull Requests are welcome!

The serverless-sentry-plugin and serverless-sentry-lib libraries are not affiliated with either Functional Software Inc., Sentry, Serverless or Amazon Web Services but developed independently and in my spare time.

Benefits

Overview

Sentry integration splits into two components:

  1. This plugin, which simplifies installation with the Serverless Framework
  2. The serverless-sentry-lib, which performs the runtime monitoring and error reporting.

For a detailed overview of how to use the serverless-sentry-lib refer to its README.md.

Installation

Usage

The Serverless Sentry Plugin allows configuration of the library through the serverless.yml and will create release and deployment information for you (if wanted). This is the recommended way of using the serverless-sentry-lib library.

▢️ Step 1: Load the Plugin

The plugin determines your environment during deployment and adds the SENTRY_DSN environment variables to your Lambda function. All you need to do is to load the plugin and set the dsn configuration option as follows:

service: my-serverless-project
provider:
  # ...
plugins:
  - serverless-sentry
custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz # URL provided by Sentry

▢️ Step 2: Wrap Your Function Handler Code

The actual reporting to Sentry happens in platform-specific libraries. Currently, only Node.js and Python are supported.

Each library provides a withSentry helper that acts as decorators around your original AWS Lambda handler code and is configured via this plugin or manually through environment variables.

For more details refer to the individual libraries' repositories:

Old, now unsupported libraries:

Node.js

For maximum flexibility, this library is implemented as a wrapper around your original AWS Lambda handler code (your handler.js or similar function). The withSentry higher-order function adds error and exception handling and takes care of configuring the Sentry client automatically.

withSentry is pre-configured to reasonable defaults and doesn't need any configuration. It will automatically load and configure @sentry/node which needs to be installed as a peer dependency.

Original Lambda Handler Code:

exports.handler = async function (event, context) {
  console.log("EVENT: \n" + JSON.stringify(event, null, 2));
  return context.logStreamName;
};

New Lambda Handler Code Using withSentry For Sentry Reporting

const withSentry = require("serverless-sentry-lib"); // This helper library

exports.handler = withSentry(async function (event, context) {
  console.log("EVENT: \n" + JSON.stringify(event, null, 2));
  return context.logStreamName;
});

ES6 Module: Original Lambda Handler Code:

export async function handler(event, context) {
  console.log("EVENT: \n" + JSON.stringify(event, null, 2));
  return context.logStreamName;
}

ES6 Module: New Lambda Handler Code Using withSentry For Sentry Reporting

import withSentry from "serverless-sentry-lib"; // This helper library

export const handler = withSentry(async (event, context) => {
  console.log("EVENT: \n" + JSON.stringify(event, null, 2));
  return context.logStreamName;
});

Once your Lambda handler code is wrapped in withSentry, it will be extended with automatic error reporting. Whenever your Lambda handler sets an error response, the error is forwarded to Sentry with additional context information. For more details about the different configuration options available refer to the serverless-sentry-lib documentation.

Plugin Configuration Options

Configure the Sentry plugin using the following options in your serverless.yml:

Sentry API access

In order for some features such as releases and deployments to work, you need to grant API access to this plugin by setting the following options:

πŸ‘‰ Important: You need to make sure you’re using Auth Tokens not API Keys, which are deprecated.

Releases

Releases are used by Sentry to provide you with additional context when determining the cause of an issue. The plugin can automatically create releases for you and tag all messages accordingly. To find out more about releases in Sentry, refer to the official documentation.

In order to enable release tagging, you need to set the release option in your serverless.yml:

custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz
    organization: my-sentry-organziation
    project: my-sentry-project
    authToken: my-sentry-api-key
    release:
      version: <RELEASE VERSION>
      refs:
        - repository: <REPOSITORY NAME>
          commit: <COMMIT HASH>
          previousCommit: <COMMIT HASH>

πŸ‘‰ Tip {"refs":["Invalid repository names: xxxxx/yyyyyyy"]}: If your repository provider is not supported by Sentry (currently only GitHub or Gitlab with Sentry Integrations) you have the following options:

  1. set refs: false, this will not automatically population the refs but also dismisses your commit id as version
  2. set refs: true and version: true to populate the version with the commit short id

If you don't specify any refs, you can also use the short notation for release and simply set it to the desired release version as follows:

custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz
    release: <RELEASE VERSION>

If you don't need or want the plugin to create releases and deployments, you can omit the authToken, organization and project options. Messages and exceptions sent by your Lambda functions will still be tagged with the release version and show up grouped in Sentry nonetheless.

πŸ‘‰ Pro Tip: The possibility to use a fixed string in combination with Serverless variables allows you to inject your release version through the command line, e.g. when running on your continuous integration machine.

custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz
    organization: my-sentry-organziation
    project: my-sentry-project
    authToken: my-sentry-api-key
    release:
      version: ${opt:sentryVersion}
      refs:
        - repository: ${opt:sentryRepository}
          commit: ${opt:sentryCommit}

And then deploy your project using the command-line options from above:

sls deploy --sentryVersion 1.0.0 --sentryRepository foo/bar --sentryCommit 2da95dfb

πŸ‘‰ Tip when using Sentry with multiple projects: Releases in Sentry are specific to the organization and can span multiple projects. Take this in consideration when choosing a version name. If your version applies to the current project only, you should prefix it with your project name.

If no option for release is provided, releases and deployments are disabled.

Source Maps

Sourcemap files can be uploaded to Sentry to display source files in the stack traces rather than the compiled versions. This only uploads existing files being output, you'll need to configure your bundling tool separately. You'll also need to have releases configured, see above.

Default options:

custom:
  sentry:
    sourceMaps: true

Add custom prefix (required if your app is not at the filesystem root)

custom:
  sentry:
    sourceMaps:
      urlPrefix: /var/task

Enabling and Disabling Error Reporting Features

In addition, you can configure the Sentry error reporting on a service as well as a per-function level. For more details about the individual configuration options see the serverless-sentry-lib documentation.

Example Configuration

# serverless.yml
service: my-serverless-project
provider:
  # ...
plugins:
  - serverless-sentry
custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz # URL provided by Sentry
    captureTimeoutWarnings: false # disable timeout warnings globally for all functions
functions:
  FuncFoo:
    handler: Foo.handler
    description: Hello World
    sentry:
      captureErrors: false # Disable error capturing for this specific function only
      captureTimeoutWarnings: true # Turn timeout warnings back on
  FuncBar:
    handler: Bar.handler
    sentry: false # completely turn off Sentry reporting

Example: Configuring Sentry based on stage

In some cases, it might be desired to use a different Sentry configuration depending on the currently deployed stage. To make this work we can use a built-in Serverless variable resolutions trick:

# serverless.yml
plugins:
  - serverless-sentry
custom:
  config:
    default:
      sentryDsn: ""
    prod:
      sentryDsn: "https://xxxx:yyyy@sentry.io/zzzz" # URL provided by Sentry

  sentry:
    dsn: ${self:custom.config.${self:provider.stage}.sentryDsn, self:custom.config.default.sentryDsn}
    captureTimeoutWarnings: false # disable timeout warnings globally for all functions

Troubleshooting

No errors are reported in Sentry

Double-check the DSN settings in your serverless.yml and compare it with what Sentry shows you in your project settings under "Client Keys (DSN)". You need a URL in the following format - see the Sentry Quick Start:

{PROTOCOL}://{PUBLIC_KEY}:{SECRET_KEY}@{HOST}/{PATH}{PROJECT_ID}

Also, make sure to add the plugin to your plugins list in the serverless.yml:

plugins:
  - serverless-sentry
custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz # URL provided by Sentry

The plugin doesn't create any releases or deployments

Make sure to set the authToken, organization as well as project options in your serverless.yml, and set release to a non-empty value as shown in the example below:

plugins:
  - serverless-sentry
custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz # URL provided by Sentry
    organization: my-sentry-organziation
    project: my-sentry-project
    authToken: my-sentry-api-key
    release: git

I'm testing my Sentry integration locally but no errors or messages are reported

Check out the filterLocal configuration setting. If you test Sentry locally and want to make sure your messages are sent, set this flag to false. Once done testing, don't forget to switch it back to true as otherwise, you'll spam your Sentry projects with meaningless errors of local code changes.

Version History

2.5.3

2.5.2

2.5.1

2.5.0

2.4.0

2.3.0

2.2.0

2.1.0

2.0.2

2.0.1

2.0.0

1.2.0

1.1.1

1.1.0

1.0.0

1.0.0-rc.4

1.0.0-rc.3

1.0.0-rc.2

1.0.0-rc.1

To-Dos

Support

That you for supporting me and my projects.