Code Monkey home page Code Monkey logo

serverless-sentry-lib's Introduction

⚡️ Serverless Sentry Lib

nodejs @sentry/node npm license dependencies prettier

About

This library simplifies the integration of Sentry's @sentry/node library with AWS Lambda. The only supported platforms of this library are the Lambda Runtimes for Node.js 12, 14, and 16. Python and Java support will require dedicated libraries. 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.
  • Catches and reports uncaught exceptions.
  • Serverless, Sentry and as well as this library are all Open Source. Yay! 🎉
  • TypeScript support

Installation

  • Install the @sentry/node and @sentry/integrations modules:
    npm install --save @sentry/node @sentry/integrations
  • Install this module:
    npm install --save serverless-sentry-lib
  • Check out the examples below on how to integrate it with your project by updating serverless.yml as well as your Lambda handler code.

Although this library is written in TypeScript, the resulting library uses exclusively Node 10 features to ensure this code can run on AWS Lambda without any additional transpiling or further processing. We also do not use any 3rd party node module other than @sentry/node and @sentry/integrations which you fully control yourself.

This library can be used standalone or as part of the Serverless Sentry Plugin.

Use as a Standalone Library

If you don't want to add another plugin to Serverless (or if you're not using the Serverless Framework), you can use this library standalone without additional dependencies (besides @sentry/node and @sentry/integrations).

If you're using the Serverless Framework, extend your serverless.yml to include additional environment variables. The only required environment variable is SENTRY_DSN to set the DSN URL for your reporting. A full list of all available environment variables is available below.

service: my-serverless-project
provider:
  # ...
  environment:
    SENTRY_ENVIRONMENT: ${opt:stage, self:provider.stage} # recommended
    SENTRY_DSN: https://xxxx:[email protected]/zzzz # URL provided by Sentry

If you are using the AWS Serverless Application Model, set the environment variables in your template.yml:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Resources:
  SomeFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: some-function/
      Handler: index.handler
      Runtime: nodejs12.x
      Environment:
        Variables:
          SENTRY_DSN: https://xxxx:[email protected]/zzzz

Environment Variables

Capturing can be controlled through the following environment variables. You can set them manually in your serverless.yml (Serverless Framework) or template.yml (AWS SAM) or let them be configured automatically using the Serverless Sentry Plugin during deployment. In addition, the library checks for the following optional variables and adds them as custom Sentry tags automatically:

Environment Variable Sentry Tag Description
SERVERLESS_SERVICE service_name Serveless service name
SERVERLESS_STAGE stage Serverless stage
SERVERLESS_ALIAS alias Serverless alias, see Serverless AWS Alias Plugin
SERVERLESS_REGION region Serverless region name

Use Together With the Serverless Sentry Plugin

The Serverless Sentry Plugin allows simpler configuration of the library through the serverless.yml and will upload your source maps automatically during deployment. This is the recommended way of using the serverless-sentry-lib library.

Instead of manually setting environment variables, the plugin determines and sets them automatically. In the serverless.yml simply 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

You can still manually set environment variables on a per-function level to overwrite the default ones. Please refer to the Serverless Sentry Plugin for full documentation of all available options.

Updating Your Code

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 it with automatic error reporting. Whenever your Lambda handler sets an error response, the error is forwarded to Sentry with additional context information.

Setting Custom Configuration Options

As shown above you can use environment variables to control the Sentry integration. In some scenarios in which environment variables are not desired or in which custom logic needs to be executed, you can also pass in configuration options to withSentry directly:

You can control how Sentry should be initialized by passing the following options:

  • sentryOptions - Additional options to set for the Sentry client, e.g. proxy settings.
  • scope - Custom scope settings.
  • filterLocal - don't report errors from local environments (defaults to true).
  • sourceMaps - Enable source maps (defaults to false) by loading the RewriteFrames Sentry integration.

Or, alternatively, you can pass in a custom, already preconfigured Sentry object. Note that Sentry needs to be properly initialized in this case:

  • sentry - Use the given Sentry instance instead of importing it automatically.

In addition, you can set any of the following options to control what events should be captured:

  • flushTimeout - How long we should wait for Sentry data to be written when shutting down the Lambda or between invocations (defaults to 2000 milliseconds).
  • autoBreadcrumbs - Automatically create breadcrumbs (see Sentry SDK docs, defaults to true).
  • captureErrors - capture Lambda errors (defaults to true).
  • captureUnhandledRejections - capture unhandled Promise rejections (defaults to true).
  • captureUncaughtException - capture uncaught exceptions (defaults to true).
  • captureMemory - monitor memory usage (defaults to true).
  • captureTimeouts - monitor execution timeouts (defaults to true).

Example

import withSentry from "serverless-sentry-lib";

// Wrap handler for automated error and exception logging
const withSentryOptions = {
  sentryOptions: {
    /* Custom Sentry configuration options */
    httpProxy: "...",
    httpsProxy: "...",
  },
  scope: {
    tags: {
      /* additional tags to send to Sentry */
      Foo: "bar",
    },
  },
  captureErrors: false,
  captureUnhandledRejections: true,
  captureUncaughtException: true,
  captureMemory: true,
  captureTimeouts: true,
};

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

Accessing the Sentry Client for Capturing Custom Messages and Exceptions

If you want to capture a message or exception from anywhere in your code, simply use the Sentry client as usual. It is a singleton instance and doesn't need to be configured again:

CommonJS

const Sentry = require("@sentry/node");
Sentry.captureMessage("Hello from Lambda!", { level: "info" });

ES6 Modules

import * as Sentry from "@sentry/node";
Sentry.captureMessage("Hello from Lambda!", { level: "info" });

For further documentation on how to use it to capture your own messages refer to docs.getsentry.com.

Capturing Unhandled Promise Rejections

When enabled all Promise rejections that aren't handled by yourself will be reported to Sentry.

Capturing Uncaught Exceptions

Typically, if your Lambda code throws an unhandled exception somewhere in the code, the invocation is immediately aborted and the function exits with a "Process exited before completing request". The plugin captures these unhandled exceptions, forwards them to Sentry and then exits the Lambda with an error code.

Local Development

By default, the library will only forward errors to Sentry when deployed on AWS Lambda, not during local development. If you want to change this behavior set the filterLocal option to false.

Detecting Slow Running Code

It's a good practice to specify the function timeout in serverless.yml to be at last twice as large as the expected maximum execution time. If you specify a timeout of 6 seconds (the default), this plugin will warn you if the function runs for 3 or more seconds. That means it's time to either review your code for possible performance improvements or increase the timeout value slightly.

Low Memory Warnings

The plugin will automatically generate a warning if the memory consumption of your Lambda function crosses 75% of the allocated memory limit. The plugin samples the amount of memory used by Node.js every 500 milliseconds (using process.memoryUsage()), independently of any garbage collection. As with all Node.js code, it is important to remember that JavaScript code runs single-threaded and the monitoring function will only be able to sample memory usage if your code is in a wait state, e.g. during database queries or when calling asynchronous functions with a callback.

Only one low memory warning will be generated per function invocation. You might want to increase the memory limit step by step until your code runs without warnings.

Turn Sentry Reporting On/Off

Sentry reporting is only enabled if you wrap your code using withSentry as shown in the examples above. In addition, error reporting is only active if the SENTRY_DSN environment variable is set or if you explicitly pass { sentryOptions: { dsn } } as configuration options. This is an easy way to enable or disable reporting as a whole or for specific functions.

In some cases, it might be desirable to disable only error reporting itself but keep the advanced features such as timeout and low memory warnings in place. This can be achieved via setting the respective options in the environment variables or withSentry during initialization:

const withSentry = require("serverless-sentry-lib");

// Wrap handler but disable error capturing; all other options will remain the default
module.exports.handler = withSentry({ captureErrors: false }, (event, context, callback) => {
  // your Lambda Functions Handler code goes here...
});

Version History

2.5.2

  • Fixed invalid @sentry/integrations peer dependency definition. Sorry :(

2.5.1

  • @sentry/integrations is a peer dependency now. Make sure to install it in your project!

2.5.0

  • Added support for @sentry/node v7. This is the recommended version now.
  • Updated dependencies

2.4.0

  • Updated dependencies

2.3.0

  • Override existing unhandledRejection and uncaughtException listeners when captureUnhandledRejections or captureUncaughtExceptions are enabled and invoke them after we handled them. At the same time we disable Sentry's default integrations for both to avoid duplicate reporting. This works around a custom listener registered by AWS Lambda internally that prevents proper automatic handling with Sentry. Thanks to ffxsam for reporting the original issue. By updating the execution order of the listeners we keep side effects to a minimum. Please report back if you encounter any weird or unexpected behavior!
  • Upgraded all dependencies, use Typescript 4.0

2.2.0

  • Reset the scope on every Lambda start (if no custom Sentry client instance is used). This should avoid breadcrumbs and extras from previous runs "bleeding" into subsequent Lambda invocations. Thanks to demsey2 for reporting the original issue.
  • Added a new flushTimeout option to control how long we want to wait for data to be written to Sentry before the Lambda shuts down or between invocations.
  • Deprecated captureMemoryWarnings and captureTimeoutWarnings in favor of new options captureMemory and captureTimeouts which allow more customization. Thanks to keanolane for suggesting custom timeouts. This only affects users invoking withSentry with custom options. If you're using serverless-sentry-plugin to set all options you won't have to change anything.
  • Fixed an issue with custom tags, extras and user traits not being set when passed as options to withSentry. Thanks to blelump for reporting and providing a pull request.

2.1.0

  • Explicitly check environment variables IS_OFFLINE and IS_LOCAL for truthy strings (yes, on, true, t, or 1). Thanks to danilofuchs for suggesting it.
  • Flush to Sentry when the Lambda function finishes but doesn't close Sentry yet as we might get called again. #23

2.0.1

  • Fixed some type resolution issues in the generated TypeScript definition file

2.0.0

  • 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! 🤗

Support

That you for supporting me and my projects.

serverless-sentry-lib's People

Contributors

arabold avatar chechu avatar dependabot[bot] avatar dijonkitchen avatar shouki-s 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

Watchers

 avatar  avatar  avatar  avatar

serverless-sentry-lib's Issues

Serverless-sentry-lib Too Large for Lambda@Edge

The issue is that the function code size for Lambda@Edge (CloudFront Lambda functions) can not exceed 1048576 bytes (which as I'm writing this, is equal to ~1.05MB). Serverless-sentry-lib is approximately 10MB, (in my case 11855943 bytes or 11.85MB). Is it at all possible for serverless-sentry-lib to be compressed to under the 1.05MB threshold, or is there an alternative to use for Lambda@Edge functions?

Sentry performance monitoring through @sentry/tracing

Thanks for your work on serverless-sentry-* ❤️


Sentry now offers performance monitoring through @sentry/tracing, and using it is a breeze. How about integrating it?

Extracts from Sentry onboarding : start by adding @sentry/tracing as a dependency:

# Using yarn
yarn add @sentry/node @sentry/tracing

# Using npm
npm install --save @sentry/node @sentry/tracing

Capture both error and performance data:

const Sentry = require("@sentry/node");
// or use es6 import statements
// import * as Sentry from '@sentry/node';

const Tracing = require("@sentry/tracing");
// or use es6 import statements
// import * as Tracing from '@sentry/tracing';

Sentry.init({
  dsn: "you know what to put there,

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});

const transaction = Sentry.startTransaction({
  op: "test",
  name: "My First Test Transaction",
});

setTimeout(() => {
  try {
    foo();
  } catch (e) {
    Sentry.captureException(e);
  } finally {
    transaction.finish();
  }
}, 99);

More info here: https://docs.sentry.io/platforms/node/#monitor-performance

unable to report errors more than once when handlers wrapped with "withSentry"

At this stage, I am not sure if the issue is with this library or @sentry/node
so I have a lambda with the following code

import withSentry from "serverless-sentry-lib";
export const handler = withSentry(async (event: S3Event, context: Context) => {
  throw new Error('test');
});

so if I call that lambda (no instance/cold start), it will report the error, but when I try again and the same lambda instance is called then the error is not reported. I thought it might be because is the same message but I tried

throw new Error(`test with dynamic error ${Date.now()}`);

and no luck with that

then I just added Sentry.init

export const handler = withSentry(async (event: S3Event, context: Context) => {
  Sentry.init({ dsn: process.env.SENTRY_DSN });
  throw new Error('test');
});

and this is reporting errors as many times as I call that lambda

my dependencies

"serverless-sentry": "^2.0.2",
"serverless-sentry-lib": "^2.0.1",
"@sentry/node": "^5.18.1",

when I try to call

let client = Sentry.getCurrentHub().getClient();
console.log(client.getOptions());

I got

{
  dsn: '...',
  release: '984ec86',
  environment: 'dev',
  defaultIntegrations: [
    InboundFilters { _options: {}, name: 'InboundFilters' },
    FunctionToString { name: 'FunctionToString' },
    Console { name: 'Console' },
    Http { name: 'Http', _breadcrumbs: true, _tracing: false },
    OnUncaughtException {
      _options: {},
      name: 'OnUncaughtException',
      handler: [Function]
    },
    OnUnhandledRejection {
      _options: [Object],
      name: 'OnUnhandledRejection'
    },
    LinkedErrors { name: 'LinkedErrors', _key: 'cause', _limit: 5 }
  ],
  enabled: false
}

that flag enabled: false doesn't exist when I call lambda first time

Cannot read property 'bind' of undefined

The sentry lib binds to the old callbacks provided through the context

These callbacks do not exist in my lambda Environment and they don't seem to be documented.

Stack trace of the error:

TypeError: Cannot read property 'bind' of undefined { error:
   TypeError: Cannot read property 'bind' of undefined
       at /var/task/src/webpack:/node_modules/serverless-sentry-lib/src/index.js:315:1
       ...

Function Timeouts: additional 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

not receiving sentry errors

having this configuration in serverless.yml:

plugins:
  - serverless-sentry
  - serverless-appsync-plugin
custom:
  sentry:
    dsn: https://xxxxxx@cccc/ssss
    environment: prod
    project: ens

and this simple lambda that should throw an error:

const Raven = require('raven');
const RavenLambdaWrapper = require('serverless-sentry-lib'); // This helper library

module.exports.handler = RavenLambdaWrapper.handler(Raven, async (event, context) => {
  // Raven.config('https://xxxxxx@cccc/ssss').install();
  console.log('!!!!', asdasd.aasd.aaa);
  return { message: 'Go Serverless! Your function executed successfully!', event };
});

I do not receive errors in sentry, unless I uncoment Raven.config('https://xxxxxx@cccc/ssss').install(); line. In both cases I'm getting this warning when lambda invoked:

Sentry disabled in local environment
[email protected] alert: no DSN provided, error reporting disabled

I'm testing this by invoking lambda locally sls invoke local -f retry. What am I doing wrong?

Missing user context when using Cognito, lambda-proxy integration, and Cognito Authorizer

When using the default lambda-proxy integration, and the built-in Cognito authorizer, the user context (Cognito user pool, username, etc.) are all undefined.

Looking at the source, this seems to be because you're checking in event.requestContext.identity (if it's set).

In my case, that object exists but the properties are mostly null. The user information is actually within event.requestContext.authorizer (though information like user pool ID doesn't exist).

Example request context object, with redacted data:

{  
   "path":"[REDACTED]",
   "accountId":"[REDACTED]",
   "resourceId":"[REDACTED]",
   "stage":"prod",
   "authorizer":{  
      "claims":{  
         "sub":"[REDACTED]",
         "email_verified":"true",
         "iss":"https://cognito-idp.eu-west-1.amazonaws.com/[REDACTED]",
         "phone_number_verified":"false",
         "cognito:username":"[REDACTED]",
         "given_name":"[REDACTED]",
         "aud":"[REDACTED]",
         "token_use":"id",
         "auth_time":"1509610756",
         "phone_number":"[REDACTED]",
         "exp":"Thu Nov 02 09:19:16 UTC 2017",
         "iat":"Thu Nov 02 08:19:16 UTC 2017",
         "family_name":"[REDACTED]",
         "email":"[REDACTED]"
      }
   },
   "requestId":"[REDACTED]",
   "identity":{  
      "cognitoIdentityPoolId":null,
      "accountId":null,
      "cognitoIdentityId":null,
      "caller":null,
      "apiKey":"",
      "sourceIp":"[REDACTED]",
      "accessKey":null,
      "cognitoAuthenticationType":null,
      "cognitoAuthenticationProvider":null,
      "userArn":null,
      "userAgent":"PostmanRuntime/6.1.6",
      "user":null
   },
   "resourcePath":"[REDACTED]",
   "httpMethod":"GET",
   "apiId":"[REDACTED]"
}

As you can see, the identity object exists but doesn't contain anything that useful.

Result in Sentry:
screen shot 2017-11-02 at 09 45 08

I can put a PR in for this, whereby I pull in user data from claims data, but wanted to check if there's anything you can think of that I'm missing?

Proposal:

Pull in claims['cognito:username'] if it's set, from event.requestContext.authorizer.claims and use that for the username property.

  • Depending on the token type used (idToken, accessToken) different claims are available, so would need to check what is available in each.
  • Is the cognito:username the value we'd want to use for the username in Sentry? There's also a unique Cognito ID, not sure how that differs. Also can log in via email/phone/federated identity, but I think that just maps back to the Cognito username?

Sentry - Event filtering

Is there anyway to use event filtering with the lib?

`import * as Sentry from "@sentry/browser";

init({
beforeSend(event, hint) {
const error = hint.originalException;
if (
error &&
error.message &&
error.message.match(/database unavailable/i)
) {
event.fingerprint = ["database-unavailable"];
}
return event;
},
});`

Customize normalizeDepth

How can I set the normalizeDepth for sentry? Is this already possible, and I'm too stupid to find it out?
I'm capturing an exception with Sentry.captureException(err, data). Data contains nested objects. In sentry this is displayed as [Object] as described in this issue

Add raven as peer dependency

The lambda handler offered by the library must be initialized with a user supplied Raven object. So the consumer is required to depend on raven.

It would be better if the library requires raven as peer dependency (maybe specifying a minimum version). This resembles the needed project setup.

Silent mode for local execution?

Hi,

when playing within local environment, ie. running tests, plenty of:

  console.warn                                                                                                        
    Sentry disabled in local environment.

usually appear making the test output effectively unreadable. Maybe we could introduce some kind of a silent mode, where these warnings are disabled?

Serverless offline / Error thrown in wrapped Handler is reported twice to sentry.io

example code:

import RavenLambdaWrapper from "serverless-sentry-lib";

const ravenConfig = {
  filterLocal: false,
  captureErrors: true,
  captureUnhandledRejections: true,
  captureMemoryWarnings: true,
  captureTimeoutWarnings: true,
  ravenClient: require("raven") // don't forget!
};

export const hello = RavenLambdaWrapper.handler(
  ravenConfig,
  async (event, context) => {
    const response = {
      body: JSON.stringify({
        message: "Go Serverless v1.0! Your function executed successfully!",
        input: event
      })
    };
    throw new Error("Hallo");

    return { ...response, statusCode: 200 };
  }
);
  1. catchen here and sent to sentry.io

    return new Promise((resolve, reject) => Raven.captureException(err, {}, () => {

  2. because all context callbacks are wrapped - same error will be sent again to sentry.io

    ravenInstalled && Raven.captureException(err, {}, () => {

the wrapper will receive the error on the callback from Serverless-offline
https://github.com/dherault/serverless-offline/blob/185df4d55b7f3a99a0119197c70898ded1e67434/src/index.js#L953

Capturing "extra" automatically

When I used serverless-sentry-lib v1 I got used to providing additional parameters to exception which were sent to sentry automatically( new Exception('Message', { additionalInfo })

This logic doesn't seem to work by default in v2

filterLocal doesn't seem to work

I tried using the filterLocal custom option but could not get it to work.

plugins:
  - serverless-content-encoding
  - serverless-sentry

custom:
  contentEncoding:
    minimumCompressionSize: 0
  sentry:
    dsn: ${env:SENTRY_DSN}
    filterLocal: false

The only way I could get pluginConfig.filterLocal to be false was by setting the environment variable SENTRY_FILTER_LOCAL=false.

SENTRY_FILTER_LOCAL=false SLS_DEBUG='*' serverless invoke local -f emailreset

Problems with @sentry/node 7

Hi, after upgrading to Version 7 we get this errors:

{ "errorType": "TypeError", "errorMessage": "Cannot read property 'Info' of undefined", "stack": [ "TypeError: Cannot read property 'Info' of undefined", " at Runtime.handler (/var/task/node_modules/serverless-sentry-lib/dist/index.js:416:43)", " at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)" ] }

It has todo with this line:

level: SentryLib.Severity.Info,

Do you have any idea how to fix this?

Error while using sourcemaps

I've been having issues using sourceMaps: true, it doesn't seem to append app://. After some debugging I found the cause to be the following line:

frame.filename = `app:///${path.basename(frame.filename)}`;

Wrapping this line in a try catch to log any errors, and throws the following error:

Cannot read properties of undefined (reading 'basename') at RewriteFrames.iteratee

In the dist/index.js file this looks like:

frame.filename = "app:///".concat(path_1.default.basename(frame.filename));

I updated this to the following to make it work:

frame.filename = "app:///".concat(path_1.basename(frame.filename));

I'm wondering if this import statement should be import * as path from 'path'.

Sentry shows logs from previous invocations

I am having a problem with withSentry wrapper. Not sure if I do something wrong or it's a bug.

If I have a lambda with the following setup

import withSentry from "serverless-sentry-lib";

export const handler = withSentry(async (event, context) => {
  console.log('start');
  Sentry.addBreadcrumb({ type: 'test' });
  throw new Error('testing Sentry');
  return;
});

and when I call that lambda first time (cold start), Sentry reports an error and I can see all logs/breadcrumbs fine when I call that lambda again (not a cold start) then in Sentry I can see logs from that invocations and from the previous one. This

To avoid that issue I had to create a new instance of Sentry every time, call init() and scope.clear(), by doing so I am losing integration with serverless-sentry plugin and I had to manually set tags etc.

Allow overrides for Timeout warning/error thresholds

It would be nice to allow dynamic threshold values for timeout warning and errors.
Even if it's following the AWS best practice, it would be nice to be able to set it differently if needed.

something like that:

if (pluginConfig.captureTimeoutWarnings) {
		// We schedule the warning at half the maximum execution time and
		// the error a few milliseconds before the actual timeout happens.
		const warningThreshold = process.env.EXECUTION_TIMEOUT_WARNING_THRESHOLD || timeRemaining / 2;
		const errorThreshold = process.env.EXECUTION_TIMEOUT_ERROR_THRESHOLD || 500;

        timeoutWarning = setTimeout(timeoutWarningFunc, warningThreshold);
		timeoutError = setTimeout(timeoutErrorFunc, Math.max(timeRemaining - errorThreshold, 0));
	}

Thanks.

Importing module exported with exports.default

Usage section of the README indicates that it can be imported as below:

const Sentry = require("@sentry/node");
const SentryLambdaWrapper = require("serverless-sentry-lib");

However, as dist/index.js is exporting the module with exports.default=, SentryLambdaWrapper has to be imported as:

const SentryLambdaWrapper = require("serverless-sentry-lib").default;

Platform
OS: Windows 10
Node.js: v12.16.1 (LTS)

1.1.0 deploy is broken

Hi!

I just ran into an issue this morning where trying to deploy code was breaking because of the latest version of serverless-sentry-lib.

package.json:main references an index.js file.

However that file doesn't exist.

The src/ files are still in there though. Maybe the build process wasn't run or something?

Thanks!

Lambda event not always included in error

When lambda returns an error, the event is missing in the report sometimes. I'm guessing it's because it's an unhandled error?

I'd like to always return the event will every error.

The extra: { }, is empty in the json.

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",
  }

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.