Edit Lambda Code

We will now edit the Lambda code again, this time in the proper way by using CDK to deploy our changes. We will be creating a custom event named ProducerLambda.

If you have closed your CloudShell tab, please open it again and make sure you are in your home directory.

If you are still within your Python virtual environment you will see that your shell prompt begins with (.env). Exit the environment with the command deactivate and return to your home directory with the command cd.`

First, we will need to open the Lambda function in CloudShell for editing:

cd dynamodb-lambda
vi lambda/producer/lambda_function.py

Next, we will need to import and initialize the New Relic Python APM agent, which is included in the New Relic layer added by the instrumentation process we performed earlier, by adding the following 3 lines of code to the top of the function:

import newrelic.agent

newrelic.agent.initialize()
@newrelic.agent.lambda_handler()

In order to begin inputting text using vi, you must enter interactive mode by hitting the i key.

Import Agent

Next, we will add a single line of code to report a custom event containing the name of the DynamoDB table being written to (you will need to scroll down a bit in the code using your down arrow key):

newrelic.agent.record_custom_event('ProducerLambda', {'producer_table_name': TABLE_NAME})

Custom Event

To save your changes in vi, hit Escape, :, wq, and hit enter/return.

Finally, To deploy your changes, enter the following commands:

source .env/bin/activate
sudo npm i -g aws-cdk
cdk deploy

Congratulations! You have successfully added custom instrumentation to your Lambda function!