Create a Lambda Function with Tracing

In this step, you will create a serverless application with tracing enabled to monitor the process when a user makes a request to the application.

  1. Go to the AWS Lambda Console and click Create a function

lambda

  1. The Create function interface appears:
  • Select Author from scratch
  • Enter MonitorFunction as the Function name
  • For Runtime, choose the latest Node.js version
  • For Architecture, select x86_64

lambda

  1. Scroll down a bit further:
  • Select Create a new role with basic Lambda permissions
  • Click Create function

lambda

  1. Once done, the newly created function will appear:

lambda

  • Click the Code tab
  • Paste the following code and click Deploy

  export async function handler(event) {
      const start = Date.now();
	
  	  await new Promise((r) => setTimeout(r, Math.random() * 300 + 300));
  	  const latency = Date.now() - start;
	
  	  console.log("Request processed in:", latency, "ms");
	
  	  console.log(JSON.stringify({
  	    "_aws": {
  	      "Timestamp": Date.now(),
  	      "CloudWatchMetrics": [
  	        {
            "Namespace": "MyApp",
	          "Dimensions": [["Service"]],
	          "Metrics": [{ "Name": "ProcessingTime", "Unit": "Milliseconds" }]
	        }
	      ]
	    },
	    "Service": "CheckoutService",
	    "ProcessingTime": latency
	  }));
	
	  return {
	    statusCode: 200,
	    body: JSON.stringify({
	      message: "Hello! Tracing + metrics working.",
	      latency
	    })
	  };	
  }

lambda

  1. Click the Configuration tab and then go to Monitoring and operations tools

lambda

  1. In the Monitoring and operations tools section, click Edit

lambda

  1. The Edit monitoring tools interface appears. Under Lambda service traces, select Enable

lambda

  1. Scroll to the bottom of the page and click Save

lambda

  1. A success message will appear:
  • Under Logs and metrics (default), you will see Enabled
  • Under Lambda service traces, you will also see Enabled

lambda

  1. Go back to MonitorFunction and click Add trigger

lambda

  1. The Add trigger interface appears:
  • For Intent, select Create a new API
  • For API type, select HTTP API
  • For Security, choose Open
  • Click Add

lambda

  1. A confirmation will appear indicating the trigger was successfully created:

lambda