Giter VIP home page Giter VIP logo

serverless-sentry-plugin's Introduction

⚡️ 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

  • Easy to use. Promised 🤞
  • Integrates with Serverless Framework as well as the AWS Serverless Application Model for AWS Lambda (though no use of any framework is required).
  • Wraps your Node.js code with Sentry error capturing.
  • Forwards any errors returned by your AWS Lambda function to Sentry.
  • Warn if your code is about to hit the execution timeout limit.
  • Warn if your Lambda function is low on memory.
  • Reports unhandled promise rejections.
  • Reports uncaught exceptions.
  • Serverless, Sentry and as well as this library are all Open Source. Yay! 🎉
  • TypeScript support

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

  • Install the @sentry/node module as a production dependency (so it gets packaged together with your source code):

    npm install --save @sentry/node
  • Install the serverless-sentry-lib as a production dependency as well:

    npm install --save serverless-sentry-lib
  • Install this plugin as a development dependency (you don't want to package it with your release artifacts):

    npm install --save-dev serverless-sentry
  • Check out the examples below on how to integrate it with your project by updating serverless.yml as well as your Lambda handler code.

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:[email protected]/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:

  • dsn - Your Sentry project's DSN URL (required)
  • enabled - Specifies whether this SDK should activate and send events to Sentry (defaults to true)
  • environment - Explicitly set the Sentry environment (defaults to the Serverless stage)

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:

  • organization - Organization name
  • project - Project name
  • authToken - API authentication token with project:write access

👉 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:[email protected]/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>
  • version - Set the release version used in Sentry. Use any of the below values:

    • git - Uses the current git commit hash or tag as release identifier.
    • random - Generates a random release during deployment.
    • true - First tries to determine the release via git and falls back to random if Git is not available.
    • false - Disable release versioning.
    • any fixed string - Use a fixed string for the release. Serverless variables are allowed.
  • refs - If you have set up Sentry to collect commit data, you can use commit refs to associate your commits with your Sentry releases. Refer to the Sentry Documentation for details about how to use commit refs. If you set your version to git (or true), the refs options are populated automatically and don't need to be set.

👉 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:[email protected]/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:[email protected]/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.

  • autoBreadcrumbs - Automatically create breadcrumbs (see Sentry Raven docs, defaults to true)
  • filterLocal - Don't report errors from local environments (defaults to true)
  • captureErrors - Capture Lambda errors (defaults to true)
  • captureUnhandledRejections - Capture unhandled Promise rejections (defaults to true)
  • captureUncaughtException - Capture unhandled exceptions (defaults to true)
  • captureMemoryWarnings - Monitor memory usage (defaults to true)
  • captureTimeoutWarnings - Monitor execution timeouts (defaults to true)

Example Configuration

# serverless.yml
service: my-serverless-project
provider:
  # ...
plugins:
  - serverless-sentry
custom:
  sentry:
    dsn: https://xxxx:[email protected]/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:[email protected]/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:[email protected]/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:[email protected]/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

  • Increased number of parallel uploads of source map artifacts for better performance.

2.5.2

  • Upload multiple source map artifacts in parallel for better performance.

2.5.1

  • Fix #63: Upload source maps serially to avoid running out of sockets.
  • Correctly disable uploading source maps if the config setting is false or unset.

2.5.0

  • Added support for uploading Source Maps to Sentry. Thanks to jonmast for the contribution.
  • Fixed an issue in the configuration validation. Thanks to DonaldoLog for the fix.
  • Fixed an issue if using
  • Updated dependencies.

2.4.0

  • Explicitly check for enabled flag. Thanks to aaronbannin for the contribution.
  • Explicit peer dependency on Serverless
  • Updated dependencies minor versions; locked TypeScript to 4.4 for now

2.3.0

  • Added configuration validation. Serverless will now warn if you pass an invalid configuration value in custom.sentry.

2.2.0

  • Added captureUncaughtException configuration option. This already exists in serverless-sentry-lib but was never exposed in the plugin.
  • Don't fail if SENTRY_DSN is not set but simply disable Sentry integration.

2.1.0

  • Support for deploying individual functions only (sls deploy -f MyFunction). Thanks to dominik-meissner!
  • Improved documentation. Thanks to aheissenberger
  • Updated dependencies.

2.0.2

  • Fixed custom release names not being set. Thanks to botond-veress!

2.0.1

  • Fixed error when creating new Sentry releases. Thanks to dryror!

2.0.0

  • This version of serverless-sentry-plugin requires the use of serverless-sentry-lib v2.x.x
  • Rewrite using TypeScript. The use of TypeScript in your project is fully optional, but if you do, we got you covered!
  • Added new default uncaught exception handler.
  • Dropped support for Node.js 6 and 8. The only supported versions are Node.js 10 and 12.
  • Upgrade from Sentry SDK raven to the Unified Node.js SDK @sentry/node.
  • Simplified integration using withSentry higher-order function. Passing the Sentry instance is now optional.
  • Thank you @aheissenberger and @Vadorequest for their contributions to this release! 🤗

1.2.0

  • Fixed a compatibility issue with Serverless 1.28.0.

1.1.1

  • Support for sls invoke local. Thanks to sifrenette for his contribution.

1.1.0

  • ⚠️ Dropped support for Node 4.3. AWS deprecates Node 4.3 starting July 31, 2018.
  • Pair with serverless-sentry-lib v1.1.x.

1.0.0

  • Version falls back to git hash if no tag is set for the current head (#15).
  • Fixed reporting bugs in the local environment despite config telling otherwise (#17). This requires an update of serverless-sentry-lib as well!

1.0.0-rc.4

  • Fixed an issue with creating random version numbers

1.0.0-rc.3

  • Allow disabling Sentry for specific functions by settings sentry: false in the serverless.yml.
  • Added support for the Serverless Offline Plugin.

1.0.0-rc.2

  • Fixed an issue with the plugin not being initialized properly when deploying an existing artifact.

1.0.0-rc.1

To-Dos

  • Bring back automatic instrumentation of the Lambda code during packaging
  • Provide CLI commands to create releases and perform other operations in Sentry
  • Ensure all exceptions and messages have been sent to Sentry before returning; see #338.

Support

That you for supporting me and my projects.

serverless-sentry-plugin's People

Contributors

aaronbannin avatar aheissenberger avatar arabold avatar botond-veress avatar dependabot[bot] avatar dominik-meissner avatar dryror avatar jonmast avatar sifrenette avatar trptcolin avatar viniciusfxavier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

serverless-sentry-plugin's Issues

setRelease is never called

Hi,

when we execute serverless deploy --package, function setRelease is never called, then cause an error at the end of the deploy

Serverless: Sentry: Creating new release "true"...
Serverless: Sentry: Deploying release "true"...
Serverless: Sentry: Received error response from Sentry:
{"detail": "The requested resource does not exist"}

because release true option in serverless.yml is never set.

It's a problem with --package option (skip packaging step) then don't call hooks after:package:init.
Thanks

Uploading source map doesn't work when deploying function only

If I deploy all project sls deploy -s mystage it works fine as expected.
However, if I try to deploy only one function with sls deploy function -f myfunction -s mystage I am getting an error Error: Invalid filename on node_modules/adm-zip/adm-zip.js:57:19

caused by this line

const zip = new AdmZip(artifact);

Because file .serverless/myFunction.zip doesn't exist. In fact, whole directory is cleaned (dropped) when I run sls deploy function.

Serverless version 3.10.1, sentry plugin 2.5.3.

I guess it should work the following - if file exists, reuse it, if not - build and pack it (and only one function). (I use package.individually = true and serverless-bundle plugin).

Seems that serverless-bundle plugin uses serverless-webpack under the hood and I have checked that during sls deploy function command a ZIP file inside directory .serverless is actually created... however after that it is deleted before hook of sentry-plugin is called... I am still not sure which issue is it exactly, which of the plugin or the framework itself...

Data scrubbing/Trace sampling feature request

I am very happy with how simple this plugin made integrating Sentry with my backend however, after successfully integrating the plugin I realized that my project has a use case for scrubbing PII and there is no support for data scrubbing and trace sampling/filtering. (Please correct me if I'm wrong)

The Sentry SDK comes out the box with the two methods that are the beforeSend method and tracesSampler method to allow filtering of transactions and a way to delete specific data points from the event object before it is sent to Sentry.

Is this a feature that can be implemented?

Feature Request: Break deploy when raven is missing as dependency

Rationale
The lambda code generated by the plugin is dependent on raven and will not ever start, but immediately break out with an exception, if the dependent module is missing. If you use the optimizer plugin, it is very hard so see what you did wrong. This is something that easily can happen when setting up a new lambda that uses the plugin.
Dependencies introduced by plugins that make the code crash when missing, should be either installed by the plugin or any use of the generated function should be denied by it.

Proposal
On function deploy the plugin should break out if raven is not found as installed dependency.

0.2 release breaks lambda

Hi,
after upgrading to 0.2 , lambda execution never completes (gives an error "Task timed out after")
downgrading back to 0.1.4, lambda function works fine .

feels like something is not being returned or callback not bing called

Incompatible with serverless-http

This plugin appears to be incompatible with serverless-http.

Example:

module.exports.api = RavenLambdaWrapper.handler(Raven, serverless(app));

it works fine when running the code locally using serverless-offline

but when running on lambda I get Task timed out after 6.01 seconds in the cloudwatch logs and a response that looks like.

{
    "message": "Internal server error"
}

Any progress on uploading source maps?

Are there still plans to work on this? If one of the repo maintainers wants to work together on this, I'm game. Right now I have to decide between using this plugin (which rocks), or the SentryWebpackPlugin (not quite as good) which does upload source maps.

AWS Lamda Production not working

serverless-sentry-lib works for me in develop but not in production, my configuration of serverless.yml:

service: serverless-api
plugins:
  - serverless-sentry
  - serverless-webpack
  - serverless-offline
provider:
  name: aws
  region: us-east-1
  runtime: nodejs6.10
  stage: production
  environment: '${file(.env.yml):${self:custom.stage}}'
custom:
  stage: '${opt:stage, self:provider.stage}'
  serverless-offline:
    port: 4000
    babelOptions:
      presets:
        - es2015
        - es2017
  sentry:
    dsn: https://(SECRET):(SECRET)@sentry.io/(SECRET)
    filterLocal: true   
  .....

verify that the DSN is correct and that the issues are coming to me (local environment), but the mistakes that I am generating in production do not arrive

'use strict'

const response = require('../../helpers/response')
import User from '../../database/models/user'

var Raven = require('raven')
var RavenLambdaWrapper = require('serverless-sentry-lib')

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

  context.callbackWaitsForEmptyEventLoop = false

  global.cb = callback

  const userid = event.pathParameters.userid

  User.findOne({ where: { userid: userid }}).then((user) => {
    if(user)
      response('user logged', 200, user)
    else
      response('user logged', 200, {error: true})

  }).catch(error => {
    response('user logged', 200, {error: true, message: error})
  })

})

Generate Error:

 UsesdfsdfdsrfindOne({ where: { userid: userid }}).then((user) => { // UsesdfsdfdsrfindOne is undefined (Exception)
    if(user)
      response('user logged', 200, user)
    else
      response('user logged', 200, {error: true})

  }).catch(error => {
    response('user logged', 200, {error: true, message: error})
  })

Packaje.json

"dependencies": {
    ....
    ....
    "raven": "2.2.1",
    "serverless-sentry-lib": "1.0.0-rc.2"
  },
  "devDependencies": {
    "serverless-sentry": "1.0.0-rc.4",
  }

Plugin defines a validation schema that is invalid

I am trying to integrate Sentry with serverless:

Serverless Version:
Framework Core: 3.1.0 Plugin: 6.0.0 SDK: 4.3.0

Serverless Sentry Plugin Version:

Production Dependency:
"serverless-sentry-lib": "^2.4.0", "@sentry/node": "^6.17.9"

Dev Dependency:

"serverless-sentry": "^2.4.0",

It returns the following error:

At least one of the plugins defines a validation schema that is invalid. Try disabling plugins one by one to identify the problematic plugin and report it to the plugin maintainers.

If I remove the sentry plugin then it works fine.

not injecting when using vandium

Started using vandium, sentry no longer injecting

executed :
sls function deploy -t -s dev
checked _tmp, code did not get modified

sample code :

'use strict';
const vandium = require('vandium');
const db = require('./db.js');
const factoryCommonData = require('./factory-common-data.js');

var _connection = {};

vandium.after(function () {
  return _connection.end();
});


module.exports.handler = vandium(main);

/***************MAIN IMPLEMENTATION********************/
 function main(event){    

  return db.GetConnection()
    .then(function (connection) {
      _connection = connection;

      return factoryCommonData.Countries(_connection);
    })
}

Feature request: Automatically warn on memory consumption

Additionally to warn as soon as half of the available timeout time has been used, it would be also critical to add an automatic warning, when 3/4 or some other configurable percentage of the provided lambda memory has been consumed, as it's hard to find out if the assigned memory is nearing the limit over time.
This happens especially when using Babel or other transformations that change their behavior on updates and create faster but more memory hungry code.

Unified Node.js SDK

Is there any way to use this plugin with the latest version of the Sentry SDK? They have deprecated the Raven version.

Cannot load config from an external file

Hello

I'm facing a problem using external .yml config files in my serverless.yml.

This works:

# serverless.yml
custom:
  sentry:	
    dsn: https://xxxx:[email protected]/zzzz
    organization: my-organziation
    project: my-project
    authToken: my-token
    release: true

This doesn't work:

# serverless.yml

custom: ${file(staging.yml)}
# staging.yml
sentry:	
  dsn: https://xxxx:[email protected]/zzzz
  organization: my-organziation
  project: my-project
  authToken: my-token
  release: true

This doesn't work either:

# serverless.yml

custom:
  env: ${file(staging.yml)}
  sentry: ${self:custom.env.sentry}
# staging.yml
sentry:	
  dsn: https://xxxx:[email protected]/zzzz
  organization: my-organziation
  project: my-project
  authToken: my-token
  release: true

The only solution is:

# serverless.yml

custom:
  env: ${file(staging.yml)}
  sentry:	
    dsn: ${self:custom.env.sentry.dsn}	
    environment: ${self:custom.env.sentry.environment}
    organization: ${self:custom.env.sentry.organization}
    project: ${self:custom.env.sentry.project}
    authToken: ${self:custom.env.sentry.authToken}
    release: ${self:custom.env.sentry.release}
# staging.yml
sentry:	
  dsn: https://xxxx:[email protected]/zzzz
  organization: my-organziation
  project: my-project
  authToken: my-token
  release: true

configPlugin() {
this.sentry = {};
if (_.has(this._custom, "sentry") && _.isPlainObject(this._custom.sentry)) {
_.assign(this.sentry, this._custom.sentry);
}
}

return this._serverless.variables.populateObject(this.sentry)
.then(populatedObject => {
this.sentry = populatedObject;

Maybe we could use this._serverless.variables.populateObject() directly on custom instead of custom.sentry (and only if sentry is an object) ?

Add support for KMS

We should encrypt at least the DSN when setting the environment variables. This would have to be supported in the platform specific libraries as well.

Direction for other language support (python)

You mention Other platforms can be added easily by providing a respective integration library. I am interested in adding support for python but am a bit lost on where exactly you foresee this library supporting other languages. I think there are two core parts to supporting a new language:

  • Exception Handler Wrapper
  • Raven setup

But I am not sure how we would traverse the python/node boundary.

Any insight?

Missing schema for `functions[].sentry` properties

Serverless Framework, over year ago was equipped with validation schema for all its service configuration. It allows to quickly pin point eventual errors developers are making when they're constructing service configurations.

It was provided with utilities for plugins so all properties that are introduced by them can also be easily accompanied with needed schema: https://www.serverless.com/framework/docs/providers/aws/guide/plugins#extending-validation-schema

Serverless Framework is about to release a v3, and with that version it's scheduled that by default any configuration errors (and undefined property is signaled as an error) will be reported with crashes and not warnings as it is in v2.

This will affect users which configure functions[].sentry, (custom namespace is excluded from that, as we allow free-form user configuration in that, still it's also good to provide schema for any properties in custom that plugin introduces).

It'll be great if plugin is upgraded and defines schemas for properties it introduces

READ.me file needs to be modified

Thank you for using a great plugin for error detection in Lambda functions via Sentry.

However, there seems to be a problem with the Releases part of the READ.me file.
I am wondering if it is correct to have a - character in front of the repository value among the settings of serverless.yml.

In my case, I'm using Circle.ci to deploy and I checked for build errors due to a - character, and I removed it and nothing happened.

It may be just my case, but if not, it would be nice to correct it.

1.0.0-rc.4

Hi,

Any chance you could release 1.0.0-rc.4 from master?

I need the "use strict"; at the top of src/git-rev.js and this isn't in the latest release.

Create release failing on v2.0.0

Just testing out updating one of my projects to use the new v2.0.0 versions of your plugin and lib and have run into an error during deployment.

Looking into the code, it seems to be failing here in the compiled code:

return [4 /*yield*/, superagent_1.default
    .post("https://sentry.io/api/0/organizations/" + organization + "/releases/")
    .set("Authorization", "Bearer " + this.sentry.authToken)
    .send(payload)];

When I change superagent_1.default to just superagent_1 (remove .default) from the code, the deployment works. I suspect its just an issue with the build process, but I'm not familiar with typescript so that's just a guess.

The full stacktrace is:

Error: Sentry: Error uploading release - TypeError: Cannot read property 'post' of undefined
    at SentryPlugin.<anonymous> (/my-project/node_modules/serverless-sentry/dist/index.js:442:31)
    at step (/my-project/node_modules/serverless-sentry/dist/index.js:44:23)
    at Object.next (/my-project/node_modules/serverless-sentry/dist/index.js:25:53)
    at /my-project/node_modules/serverless-sentry/dist/index.js:19:71
    at new Promise (<anonymous>)
    at __awaiter (/my-project/node_modules/serverless-sentry/dist/index.js:15:12)
    at SentryPlugin.createSentryRelease (/my-project/node_modules/serverless-sentry/dist/index.js:408:16)
    at SentryPlugin.<anonymous> (/my-project/node_modules/serverless-sentry/dist/index.js:100:59)
    at step (/my-project/node_modules/serverless-sentry/dist/index.js:44:23)
    at Object.next (/my-project/node_modules/serverless-sentry/dist/index.js:25:53)
    at /my-project/node_modules/serverless-sentry/dist/index.js:19:71
    at new Promise (<anonymous>)
    at __awaiter (/my-project/node_modules/serverless-sentry/dist/index.js:15:12)
    at Object.after:deploy:deploy [as hook] (/my-project/node_modules/serverless-sentry/dist/index.js:97:57)
    at /my-project/node_modules/serverless/lib/classes/PluginManager.js:490:55
    at tryCatcher (/my-project/node_modules/serverless/node_modules/bluebird/js/release/util.js:16:23)
    at Object.gotValue (/my-project/node_modules/serverless/node_modules/bluebird/js/release/reduce.js:168:18)
    at Object.gotAccum (/my-project/node_modules/serverless/node_modules/bluebird/js/release/reduce.js:155:25)
    at Object.tryCatcher (/my-project/node_modules/serverless/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/my-project/node_modules/serverless/node_modules/bluebird/js/release/promise.js:547:31)
    at Promise._settlePromise (/my-project/node_modules/serverless/node_modules/bluebird/js/release/promise.js:604:18)
    at Promise._settlePromise0 (/my-project/node_modules/serverless/node_modules/bluebird/js/release/promise.js:649:10)
    at Promise._settlePromises (/my-project/node_modules/serverless/node_modules/bluebird/js/release/promise.js:729:18)
    at _drainQueueStep (/my-project/node_modules/serverless/node_modules/bluebird/js/release/async.js:93:12)
    at _drainQueue (/my-project/node_modules/serverless/node_modules/bluebird/js/release/async.js:86:9)
    at Async._drainQueues (/my-project/node_modules/serverless/node_modules/bluebird/js/release/async.js:102:5)
    at Immediate.Async.drainQueues (/my-project/node_modules/serverless/node_modules/bluebird/js/release/async.js:15:14)
    at processImmediate (internal/timers.js:456:21)
    at process.topLevelDomainCallback (domain.js:137:15)

Cannot catch unhandled promise rejections

This is my endpoint code (using Serverless Framework):

import serverless from 'serverless-http';
import app from './app'; // express app
import withSentry from 'serverless-sentry-lib';

export const handler = withSentry(serverless(app));

I figured this would work since this plugin is meant for serverless, but unfortunately it doesn't handle unexpected/uncaught errors. Is there something else I need to do?

Error: Cannot find module 'raven'

After following the setup instructions and deploying a function, all requests return the following error:

{
  "errorMessage": "Cannot find module 'raven'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._load (module.js:276:25)",
    "Module.require (module.js:353:17)",
    "require (internal/module.js:12:17)",
    "Object.<anonymous> (/var/task/properties/_serverless_handler.js:1550:19)",
    "Module._compile (module.js:409:26)",
    "Object.Module._extensions..js (module.js:416:10)",
    "Module.load (module.js:343:32)",
    "Function.Module._load (module.js:300:12)",
    "Module.require (module.js:353:17)"
  ]
}

Issue not tracked in Sentry

Hi, I've followed the instructions and installed the plugin on Lambda.
However, when I then trigger a very obvious error, it's not picked up in Sentry.

Here's my code:

'use strict';
const SparkPost = require('sparkpost');
const { decrypt, } = require('../crypto.js');
const RavenLambdaWrapper = require("serverless-sentry-lib");

// Wrap handler for automated error and exception logging
const ravenConfig = {
  captureErrors: true,
  captureUnhandledRejections: true,
  captureMemoryWarnings: true,
  captureTimeoutWarnings: true,
  ravenClient: require("raven") // don't forget!
};

module.exports.index = RavenLambdaWrapper.handler(ravenConfig, (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = true;
  const keys = event.requestContext.authorizer;
  const body = JSON.parse(event.body);
  console.log('event', JSON.stringify(body, 3));
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: '',
  };

  const client = new SparkPost(keys.SparkPostKey);

  const RECIPIENT = body.RECIPIENT;
  const TEMPLATE_ID = body.TEMPLATE_ID;
  const CAMPAIGN_ID = body.CAMPAIGN_ID;
  const SUBSTITUTION_DATA = body.SUBSTITUTION_DATA;

  try {
    if (SUBSTITUTION_DATA && SUBSTITUTION_DATA.confirmation_link) {
      SUBSTITUTION_DATA.confirmation_link = decrypt(SUBSTITUTION_DATA.confirmation_link);
    }
  } catch (err) {
    console.log('to decryption err', err);
    response.statusCode = 400;
    response.body = JSON.stringify({
      status: 'Failed',
      error: 'Decryption error in \'confirmation_link\'',
    });
    return callback(null, response);
  }

  client.transmissions.send({
    options: {
      track_opens: true,
      track_clicks: true,
      transactional: true,
      ip_pool: "trans2"
    },
    campaign_id: CAMPAIGN_ID,
    content: {
      template_id: TEMPLATE_ID
    },
    substitution_data: SUBSTITUTION_DATA,
    recipients: RECIPIENT
  })
    .then(data => {
      console.log("Email has been sent. ", data);
      response.body = JSON.stringify({
        success: true,
        data: data,
      });
      callback(null, response);

    })
    .catch(err => {
      console.log(err);
      response.statusCode = 400;
      response.body = JSON.stringify({
        success: false,
        error: err,
      });
      callback(null, response);

    });

});

This is my serverless.yml file

service: saas-service

plugins:
  - serverless-webpack
  - serverless-sentry

provider:
  name: aws
  runtime: nodejs8.10
  region: ${self:custom.environment.AwsRegion}
  stage: ${opt:stage}
  timeout: 30
  memorySize: 512

custom:
  environment: ${file(./config.json):${opt:stage}}
  webpack:
    webpackConfig: webpack.config.js
    includeModules:
      forceExclude:
        - aws-sdk
        - crypto
  sentry:
    dsn: https://[email protected]/YYY # URL provided by Sentry

functions:
  Authorizer:
    handler: functions/authorizer/authorizer.index
    environment:
      Environment: ${opt:stage}

  ConfirmationEmail:
    handler: functions/mail/confirmation_email.index
    events:
    - http:
        path: confirmation_email/
        method: post
        cors: true
        authorizer:
          name: Authorizer
          resultTtlInSeconds: 0
          identitySource: method.request.header.Authorization
          type: token
    environment:
      Environment: ${opt:stage}

resources:
	Resources:
	  GatewayResponseDefault4XX:
	    Type: 'AWS::ApiGateway::GatewayResponse'
	    Properties:
	      ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
	      ResponseType: DEFAULT_4XX
	      RestApiId:
	        Ref: 'ApiGatewayRestApi'

If I send a wrong SUBSTITUTION_DATA.confirmation_link the Lambda functions breaks (correctly) and I can see the log in CloudWatch, but Sentry doesn't pick anything up.
Ideas?

Sentry: Error uploading sourcemap file - Error: connect EADDRNOTAVAIL 35.188.42.15:443 - Local

Hi,

A few days from now we started to get this error on our pipelines:

Error ---------------------------------------------------
 
  Error: Sentry: Error uploading sourcemap file - Error: connect EADDRNOTAVAIL 35.188.42.15:443 - Local (172.17.0.2:0)
      at SentryPlugin.<anonymous> (/builds/services/node_modules/serverless-sentry/dist/index.js:603:31)
      at step (/builds/services/node_modules/serverless-sentry/dist/index.js:44:23)
      at Object.throw (/builds/services/node_modules/serverless-sentry/dist/index.js:25:53)
      at rejected (/builds/services/node_modules/serverless-sentry/dist/index.js:17:65)
      at processTicksAndRejections (internal/process/task_queues.js:95:5)
 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com
 
  Your Environment Information ---------------------------
     Operating System:          linux
     Node Version:              14.19.3
     Framework Version:         2.72.3 (local)
     Plugin Version:            5.5.4
     SDK Version:               4.3.2
     Components Version:        3.18.2

This is what our dependencies look like at the moment:

    "@sentry/integrations": "^7.2.0",
    "@sentry/node": "^7.2.0",
    "serverless-sentry-lib": "^2.5.0",
    "serverless-sentry": "^2.5.0",

We even tried to disable this functionality by adding the environment variable SENTRY_SOURCEMAPS or adding the custom config:

sentry:
    sourceMaps: false

But it runs regardless and ignores the flag. Do you have any idea what is happening and how to work around this?

[bug] [regression] Error: Sentry: Error deploying release - Error: Too Many Requests

Hello!

We started to getting "too many requests" error from Sentry after last update.
"You are attempting to use this endpoint too frequently. Limit is 40 requests in 1 seconds"

I can assume it may happen because of latest change 5140c0d

Two things I can propose here:

  • To decrease it to more reasonable standard value.
  • To parameterize it to have more control on it (put 999 if I am sure what I am doing or 1 if want to disable parallelism completely).

For me concurrency 5 was reasonable default, why it was changed to 50, did it really give meaningful performance gain?

Uploading source maps to sentry when using serverless-plugin-typescript

Hi,

Just wondering if anyone has managed to get source map uploads to sentry working when using ts, and serverless-plugin-typescript to build and deploy ts lambdas. Serverless plugin typescript temporarily creates its outputs in a .build directory but I think this may be deleted after the packaing phase completes in sls and before the sentry plugin runs.

Git version without Github

I would like to use git versions, but I can't since it populates automatically the refs option. My problem is that we're not using Github, but a private Gitlab (sob). So the configuration is rejected by Sentry saying it doesn't know the related Github repo.

Serverless: Sentry: Creating new release "v0.23.0-rc1"...
Serverless: Sentry: Received error response from Sentry:
{"refs": ["Invalid repository names: my_company/my_repo"]}

refs - If you have set up Sentry to collect commit data, you can use commit refs to associate your commits with your Sentry releases. Refer to the Sentry Documentation for details about how to use commit refs. If you set your version to git (or true), the refs options are populated automatically and don't need to be set.

Is there a way to enable the git version feature (i.e. using the git commit hash or version if any) without populating the refs ?

Add enable config

Specifies whether this SDK should activate and send events to Sentry.
Disabling the SDK reduces all overhead from instrumentation, collecting breadcrumbs and capturing events.

Defaults to true.

JS example:
image

Add custom User Context

I am not using Cognito for Lambda authentication, but using custom authentication using Lambda NodeJS.

How I can set additional context such as:

  Raven.setContext({
    user: {
      email: '[email protected]',
      id: '123'
    }
  });

Thank your very much

Serverless deployment fails with "fatal: No names found, cannot describe anything."

Since the latest minor version change (from 2.3.0 to 2.4.0) the serverless deployment process on the project I am working on is failing with the following error message:

Error: Sentry: No Git available - Error: Command failed: git describe --exact-match --tags HEAD
fatal: No names found, cannot describe anything.

It appears that the cause is running git describe on a git repository that has no tags; the repo I'm working on has no tags.

And I can see from 612f76d#diff-1bcdce6971f2549017c3a649865c9921b7e765fb368eb43e78fbc373a779ba31 that this package is no longer suppressing errors.

Can you suggest how to proceed?

Javascript Sourcemap upload to sentry.io

Are there any plans to support the upload of javascript sourcemaps?
https://docs.sentry.io/clients/javascript/sourcemaps/

I user webpack & uglify on my project and this would help to show the original source code on exceptions

Is not possible at the moment as sentry.io does not support this for node :-(
getsentry/sentry#2632

I tried to upload thru the sentry cli and tested with webpack devtool: 'source-map' and devtool: 'inline-source-map' but nothing worked as this feature is deactivated for node project globally

Issue : For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

Following the instructions this is what I have:

serverless.yml
custom:
  variables: ${file(config/serverless/${self:provider.stage}.yml)}
  sentry:
      dsn: "https://[email protected]/xxxxxxxx"

plugins:
  - serverless-delete-loggroups
  - serverless-plugin-typescript
  - serverless-plugin-existing-s3
  - serverless-sentry
#  - serverless-sentry-lib

And this is how I am using the code to send the message to Sentry:

...
import * as Raven from 'raven';
Raven.config('https://[email protected]/xxxxxxxx').install();
Raven.captureException('test 7');

This is the error I am getting when run dev in local and in AWS:

sls invoke local --function functionName --stage dev --path tests/events/test.json --profile testprof

Error --------------------------------------------------
 
  data-pipeline-qa Unable to validate the following destination configurations
 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

After I set the variable SLS_DEBUG to "*" like this:

  environment:
      SLS_DEBUG: "*"

I am still getting the same error.

But if I change the serverless.yml to:

plugins:
  - serverless-delete-loggroups
  - serverless-plugin-typescript
  - serverless-plugin-existing-s3
#  - serverless-sentry
  - serverless-sentry-lib
#  - serverless-plugin-optimize

It runs ok. I can see the message in Sentry.

But if I try do deploy for test inside AWS I get the error:

Error --------------------------------------------------
 
  data-pipeline-qa Unable to validate the following destination configurations
 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable. 

AND if I set the value for SLS_DEBUG as required in the error to

  environment:
    SLS_DEBUG: "*"

It runs ok locally - I mean I can see the message inside Sentry,

But if I try to deploy in AWS i get the previous error again:

Error --------------------------------------------------
 
  data-pipeline-qa Unable to validate the following destination configurations
 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

The plugin shouldn't send latest git tag when i's not the latest commit

I have the following commits:

  • 5ec98be (HEAD -> serverless, origin/serverless) RCH-183 Try Sentry git version
  • 66b3337 (tag: v0.23.0-rc1) v0.23.0-rc1
  • 8b0db54 RCH-183 Add more lambda memory for more speed
  • ...

During serverless deployment, the release pushed to Sentry is v0.23.0-rc1, which corresponds to the latest tag. But that's not the latest commit.

Serverless: Sentry: Creating new release "v0.23.0-rc1"...
Serverless: Sentry: Received error response from Sentry:
{"refs": ["Invalid repository names: my_company/my_repo"]}

I think we should push the latest git tag only when it's on HEAD.

Using random version make serverless configuration inconsistant

When configuring release version as "random", the underlying serverless configuration is invalid.

In invalid cloudformation-template-update-stack.json, we get something like:

    "Environment": {
      "Variables": {
        "NODE_ENV": "production",
        "SENTRY_DSN_CLIENT": "...",
        "SENTRY_DSN": "..."
        "SENTRY_RELEASE": {
          "isFulfilled": true,
          "isRejected": false,
          "fulfillmentValue": "206cad0e9012458e88835839fd8aab33"
        },

This fails on deployment because an environment variable cannot be (obviously) an object.

Global Config

Great Plugin! I would like to ability to set options in the custom object in s-project.json instead of s-function.json Any guidance on how to do this?

Function Timeouts lack of information

In case of a function timeout the information provided is very modest.

The information is as follows:
{ Records: [ [Object] ] }

It would be good to see the whole output as a string, is there a way to do so?

Thank you! Alex

Repository name capturing from remote is wrong

I have repository in Gitlab called [email protected]:org/group/subgroup/project.git.
When trying to use the plugin with releases configuration I am bad request from Sentry with similar message

{"refs":["Invalid repository names: subgroup / project"]}

Seems it's because of regular expression here

let repository = /[:/]([^/]+\/[^/]+?)(?:\.git)?$/i.exec(origin)?.[1];

I am not sure what was the motivation for such capturing group as ([^/]+\/[^/]+?), so me just putting (.+?) is enough and works... this expression allows only one / symbol, though it may be few of them in between. What I need is to extract full repository name like org/group/subgroup/project.

Is it a bug? Seems that putting repository name manually into serverless.yaml fixes it.

Add Custom Tags

Is there a mechanism to add custom tags to the scope of the sentry object?

filterLocal: true gets ignored

What is wrong with my code that the configuration for "filterLocal" gets ignored?
Or how can I access the right instance of the wrapper in my App Object?

This is my excerpt from serverless.yml:

  sentry:
    dsn: https://[email protected]/YYYYY
    organization: ORG
    project: PRJ
    authToken: *****
    release: true
    filterLocal: true

starting server less offline:

...
Serverless: GET /getYYYY/b/a (λ: getYYYY)
Serverless: The first request might take a few extra seconds
Sentry **disabled in local environment**
...

this is the code in the handler.js:

import 'source-map-support/register';
import Raven from 'raven';
import RavenLambdaWrapper from 'serverless-sentry-lib';

import AppHandler from './app';

const handler = new AppHandler({});
export const getYYYY = RavenLambdaWrapper.handler(Raven, handler.getwlanuser() );

this is the code in the app.js:

import Raven from 'raven';

export default class {

  getYYYY() {
    return (event, context, cb) => { 
       Raven.captureMessage('Test Start');
    }
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.