How to use Sentry to monitor your serverless app
In this example we will look at how to use Sentry to monitor the Lambda functions in your SST serverless application.
Requirements
- Node.js >= 10.15.1
- We’ll be using Node.js (or ES) in this example but you can also use TypeScript
- An AWS account with the AWS CLI configured locally
- A Sentry account
What is Sentry
When a serverless app is deployed to production, it’s useful to be able to monitor your Lambda functions. There are a few different services that you can use for this. One of them is Sentry. Sentry offers Serverless Error and Performance Monitoring for your Lambda functions.
Create an SST app
Let’s start by creating an SST app.
$ npx create-serverless-stack@latest sentry
$ cd sentry
By default our app will be deployed to the us-east-1
AWS region. This can be changed in the sst.json
in your project root.
{
"name": "sentry",
"region": "us-east-1",
"main": "stacks/index.js"
}
Project layout
An SST app is made up of a couple of parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
src/
— App CodeThe code that’s run when your API is invoked is placed in the
src/
directory of your project.
Create our infrastructure
Our app is going to be a simple API that returns a Hello World response.
Creating our API
Let’s add the API.
Add this in stacks/MyStack.js
.
import * as sst from "@serverless-stack/resources";
export default class MyStack extends sst.Stack {
constructor(scope, id, props) {
super(scope, id, props);
// Create a HTTP API
const api = new sst.Api(this, "Api", {
routes: {
"GET /": "src/lambda.handler",
},
});
// Show the endpoint in the output
this.addOutputs({
ApiEndpoint: api.url,
});
}
}
We are using the SST Api
construct to create our API. It simply has one endpoint at the root. When we make a GET
request to this endpoint the function called handler
in src/lambda.js
will get invoked.
Your src/lambda.js
should look something like this.
export async function handler(event) {
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: `Hello, World! Your request was received at ${event.requestContext.time}.`,
};
}
Setting up our app with Sentry
We are now ready to use Sentry to monitor our API. Sentry offers Serverless Error and Performance Monitoring for your Lambda functions. Integration is done through a Lambda Layer.
Go to the Settings > Projects. Select the project. Then scroll down to SDK SETUP and select Client Keys (DSN). And copy the DSN.
Create a .env.local
file with the SENTRY_DSN
in your project root.
SENTRY_DSN=https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@xxxxxxxx.ingest.sentry.io/xxxxxxx
Note that, this file should not be committed to Git. If you are deploying the app through a CI service, configure the SENTRY_DSN
as an environment variable in the CI provider. If you are deploying through Seed, you can configure this in your stage settings.
Next, you’ll need to add the Sentry Lambda layer in your app.
Head over to the Sentry docs and get the layer they provide. Select your region and copy the layer ARN.
You can then set the layer for all the functions in your stack using the addDefaultFunctionLayers
and addDefaultFunctionEnv
. Note we only want to enable this when the function is deployed, and not when using Live Lambda Dev.
Add the following below the super(scope, id, props)
line in stacks/MyStack.js
.
// Configure Sentry
if (!scope.local) {
const sentry = LayerVersion.fromLayerVersionArn(
this,
"SentryLayer",
`arn:aws:lambda:${scope.region}:943013980633:layer:SentryNodeServerlessSDK:35`
);
this.addDefaultFunctionLayers([sentry]);
this.addDefaultFunctionEnv({
SENTRY_DSN: process.env.SENTRY_DSN,
SENTRY_TRACES_SAMPLE_RATE: "1.0",
NODE_OPTIONS: "-r @sentry/serverless/dist/awslambda-auto",
});
}
Note that addDefaultFunctionLayers
and addDefaultFunctionEnv
only affects the functions added after it’s been called. So make sure to call it at the beginning of your stack definition if you want to monitor all the Lambda functions in your stack.
Also, replace the layer ARN with the one that we copied above.
Wrapping our Lambda handler
Next, we’ll instrument our Lambda functions by wrapping them with the Sentry handler.
Replace the code in src/lambda.js
with this.
import Sentry from "@sentry/serverless";
export const handler = Sentry.AWSLambda.wrapHandler(async (event) => {
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: `Hello, World! Your request was received at ${event.requestContext.time}.`,
};
});
Let’s test what we have so far.
Deploy your app
We need to deploy the API in order to track any errors.
Run the following.
$ npx sst deploy
The first time you run this command it’ll take a couple of minutes to deploy your app from scratch.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-sentry-my-stack: deploying...
✅ dev-sentry-my-stack
Stack dev-sentry-my-stack
Status: deployed
Outputs:
ApiEndpoint: https://753gre9wkh.execute-api.us-east-1.amazonaws.com
The ApiEndpoint
is the API we just created. Let’s test the endpoint.
Open the URL in your browser. You should see the Hello World message.
Now head over to your Sentry dashboard to start exploring key metrics like the execution duration, failure rates, and transactions per minute. You can also click through to inspect specific errors.
Cleaning up
Finally, you can remove the resources created in this example using the following.
$ npx sst remove
Conclusion
And that’s it! We’ve got a serverless API monitored with Sentry. It’s deployed to production, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
Example repo for reference
github.com/serverless-stack/serverless-stack/tree/master/examples/sentryFor help and discussion
Comments on this exampleMore Examples
APIs
-
REST API
Building a simple REST API.
-
WebSocket API
Building a simple WebSocket API.
-
TypeScript REST API
Building a REST API with TypeScript.
-
Go REST API
Building a REST API with Golang.
-
Custom Domains
Using a custom domain in an API.
Web Apps
Mobile Apps
GraphQL
Databases
-
DynamoDB
Using DynamoDB in a serverless API.
-
MongoDB Atlas
Using MongoDB Atlas in a serverless API.
-
PostgreSQL
Using PostgreSQL and Aurora in a serverless API.
-
CRUD DynamoDB
Building a CRUD API with DynamoDB.
Authentication
Using AWS IAM
-
Cognito IAM
Authenticating with Cognito User Pool and Identity Pool.
-
Facebook Auth
Authenticating a serverless API with Facebook.
-
Google Auth
Authenticating a serverless API with Google.
-
Twitter Auth
Authenticating a serverless API with Twitter.
-
Auth0 IAM
Authenticating a serverless API with Auth0.
Using JWT
-
Cognito JWT
Adding JWT authentication with Cognito.
-
Auth0 JWT
Adding JWT authentication with Auth0.
Async Tasks
-
Cron
A simple serverless Cron job.
-
Queues
A simple queue system with SQS.
-
Pub/Sub
A simple pub/sub system with SNS.
-
Resize Images
Automatically resize images uploaded to S3.
Editors
-
Debug With VS Code
Using VS Code to debug serverless apps.
-
Debug With WebStorm
Using WebStorm to debug serverless apps.
-
Debug With IntelliJ
Using IntelliJ IDEA to debug serverless apps.
Monitoring
-
Datadog
Using Datadog to monitor a serverless app.
Miscellaneous
-
Lambda Layers
Using the chrome-aws-lambda layer to take screenshots.
-
Middy Validator
Use Middy to validate API request and responses.