Skip to content

Instantly share code, notes, and snippets.

@markilott
Last active October 30, 2022 06:58
Show Gist options
  • Save markilott/65e009c695c6fae843dc8a3d4d0137f7 to your computer and use it in GitHub Desktop.
Save markilott/65e009c695c6fae843dc8a3d4d0137f7 to your computer and use it in GitHub Desktop.
/** Full code available here: https://github.com/markilott/aws-cdk-lambda-powertools/blob/main/src/lambda/read-data/index.ts */
import { AWSError, DynamoDB } from 'aws-sdk';
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
import { Metrics, MetricUnits, logMetrics } from '@aws-lambda-powertools/metrics';
import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer';
import middy from '@middy/core';
/** Instantiate the PowerTools instances */
const logger = new Logger();
const tracer = new Tracer();
const metrics = new Metrics();
/** Wrap the AWS client in the tracer */
const docClient = tracer.captureAWSClient(new DynamoDB.DocumentClient({
region: process.env.AWS_REGION,
}));
/**
* Write a record to the DynamoDb table and create CloudWatch Logs.
* This function is used for the Create and Update methods.
*/
const lambdaHandler = async (event: EventProps): Promise<FunctionResult> => {
const { params, context } = event;
const { requestId } = context;
const {
correlationId = requestId,
} = params;
/**
* Add a correlationId (tracking code).
* correlationId will be included with all logs, metrics and traces
* and will be searchable/filterable in the CloudWatch console.
*/
tracer.putAnnotation('correlationId', correlationId);
logger.appendKeys({ correlationId });
metrics.addMetadata('correlationId', correlationId);
try {
/** ... application logic that sets a colour for an item */
/** Write JSON log with the result */
logger.info('Colour', { data: colour });
/**
* Write the item colour to a custom metric.
* This metric will have the "feature" dimension in addition to defaults.
*/
const colourMetric = metrics.singleMetric();
colourMetric.addDimension('feature', 'colourPicker');
colourMetric.addMetric(colour, MetricUnits.Count, 1);
/** ... write the item to DynamoDb, then log result if debugging is enabled */
logger.debug('DynamoDb Item', { data: item });
return result;
} catch (err) {
/** Adding the function_name dimension to match the default used in the PowerTools cold start metric */
metrics.addDimension('function_name', process.env.AWS_LAMBDA_FUNCTION_NAME || 'unknown');
if (statusCode === 400) {
/** Add WARN level log and metric count for client errors */
logger.warn(errorMessage, { data: params });
metrics.addMetric('WARNING', MetricUnits.Count, 1);
} else {
/** Add ERROR level log and metric count for internal errors */
logger.error(err.message, err);
metrics.addMetric('ERROR', MetricUnits.Count, 1);
}
throw err;
}
};
/** Wrap the handler with middy and inject PowerTools */
export const handler = middy(lambdaHandler)
.use(captureLambdaHandler(tracer))
/** clearState resets the correlationId for each invocation */
.use(injectLambdaContext(logger, { clearState: true }))
.use(logMetrics(metrics, { captureColdStartMetric: true }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment