-
Notifications
You must be signed in to change notification settings - Fork 156
fix: updated CDK examples to remove old references & improve comments #439
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
7e58cb6
4ac474d
5e033c6
13c6103
9c2a418
9b732a3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,26 @@ | ||
import { Tracer } from '@aws-lambda-powertools/tracer'; | ||
import { Callback, Context } from 'aws-lambda'; | ||
import { Context } from 'aws-lambda'; | ||
import { Events, LambdaInterface } from '@aws-lambda-powertools/commons'; | ||
import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; | ||
import { Logger } from '@aws-lambda-powertools/logger'; | ||
|
||
const namespace = 'CDKExample'; | ||
const serviceName = 'MyFunctionWithDecorator'; | ||
|
||
const metrics = new Metrics({ namespace: namespace, service: serviceName }); | ||
const metrics = new Metrics({ namespace: namespace, serviceName: serviceName }); | ||
const logger = new Logger({ logLevel: 'INFO', serviceName: serviceName }); | ||
const tracer = new Tracer({ serviceName: serviceName }); | ||
|
||
export class MyFunctionWithDecorator { | ||
@tracer.captureLambdaHanlder() | ||
export class MyFunctionWithDecorator implements LambdaInterface { | ||
// We decorate the handler with the various decorators | ||
@tracer.captureLambdaHandler() | ||
@logger.injectLambdaContext() | ||
@metrics.logMetrics({ | ||
captureColdStartMetric: true, | ||
raiseOnEmptyMetrics: true, | ||
throwOnEmptyMetrics: true, | ||
defaultDimensions: { environment: 'example', type: 'withDecorator' }, | ||
}) | ||
public handler(_event: unknown, _context: Context, _callback: Callback<unknown>): void | Promise<unknown> { | ||
public async handler(event: typeof Events.Custom.CustomEvent, context: Context): Promise<unknown> { | ||
// ### Experiment logger | ||
logger.addPersistentLogAttributes({ | ||
testKey: 'testValue', | ||
|
@@ -36,28 +38,34 @@ export class MyFunctionWithDecorator { | |
metricWithItsOwnDimensions.addMetric('single-metric', MetricUnits.Percent, 50); | ||
|
||
// ### Experiment tracer | ||
tracer.putAnnotation('Myannotation', 'My annotation\'s value'); | ||
|
||
// Create subsegment & set it as active | ||
const segment = tracer.getSegment(); // This is the facade segment (the one that is created by Lambda & that can't be manipulated) | ||
const subsegment = segment.addNewSubsegment('MySubSegment'); | ||
// Service & Cold Start annotations will be added for you by the decorator/middleware | ||
|
||
// These traces will be added to the main segment (## index.handler) | ||
tracer.putAnnotation('awsRequestId', context.awsRequestId); | ||
tracer.putMetadata('eventPayload', event); | ||
|
||
// Create another subsegment & set it as active | ||
const handlerSegment = tracer.getSegment(); // This is the custom segment created by Tracer for you (## index.handler) | ||
const subsegment = handlerSegment.addNewSubsegment('### MySubSegment'); | ||
tracer.setSegment(subsegment); | ||
// TODO: Add the ColdStart annotation !!! NOT POSSIBLE | ||
// tracer.putAnnotation('ColdStart', tracer); | ||
|
||
let res; | ||
try { | ||
throw new Error('test'); | ||
// Add the response as metadata | ||
res = { foo: 'bar' }; | ||
} catch (err) { | ||
Comment on lines
54
to
56
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same as above. Why try/catch without throw? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This one has the throw at L57. |
||
// Add the error as metadata | ||
subsegment.addError(err as Error, false); | ||
throw err; | ||
} finally { | ||
// Close the subsegment you created (### MySubSegment) | ||
subsegment.close(); | ||
// Set back the original segment as active (## index.handler) | ||
tracer.setSegment(handlerSegment); | ||
// The main segment (facade) will be closed for you at the end by the decorator/middleware | ||
} | ||
|
||
// Close subsegment | ||
subsegment.close(); | ||
|
||
return res; | ||
} | ||
} | ||
|
||
export const handlerClass = new MyFunctionWithDecorator(); | ||
export const handler = handlerClass.handler; | ||
export const myFunction = new MyFunctionWithDecorator(); | ||
export const handler = myFunction.handler; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,73 @@ | ||
import middy from '@middy/core'; | ||
import { Callback, Context } from 'aws-lambda'; | ||
import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; | ||
import { Context } from 'aws-lambda'; | ||
import { Events } from '@aws-lambda-powertools/commons'; | ||
import { Metrics, MetricUnits, logMetrics } from '@aws-lambda-powertools/metrics'; | ||
import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer'; | ||
import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger'; | ||
|
||
const metrics = new Metrics({ namespace: 'CDKExample', service: 'withMiddy' }); // Sets metric namespace, and service as a metric dimension | ||
const namespace = 'CDKExample'; | ||
const serviceName = 'MyFunctionWithMiddyMiddleware'; | ||
|
||
type CustomEvent = { | ||
throw: boolean | ||
}; | ||
const metrics = new Metrics({ namespace: namespace, serviceName: serviceName }); | ||
const logger = new Logger({ logLevel: 'INFO', serviceName: serviceName }); | ||
const tracer = new Tracer({ serviceName: serviceName }); | ||
|
||
class MyFunctionWithDecorator { | ||
const lambdaHandler = async (event: typeof Events.Custom.CustomEvent, context: Context) => { | ||
// ### Experiment with Logger | ||
// AWS Lambda context is automatically injected by the middleware | ||
|
||
@metrics.logMetrics({ captureColdStartMetric: true }) | ||
public handler(_event: CustomEvent, _context: Context, _callback: Callback<unknown>): void | Promise<unknown> { | ||
metrics.addMetric('test-metric', MetricUnits.Count, 10); | ||
if (_event.throw) { | ||
throw new Error('Test error'); | ||
} | ||
} | ||
} | ||
logger.addPersistentLogAttributes({ | ||
testKey: 'testValue', | ||
}); | ||
logger.debug('This is an DEBUG log'); // Won't show because we pass logLevel: 'INFO' in the constructor. | ||
logger.info('This is an INFO log'); | ||
logger.warn('This is an WARN log'); | ||
logger.error('This is an ERROR log'); | ||
|
||
const handler = middy(async (_event, _context) => { | ||
// ### Experiment with Metrics | ||
// Default metrics, cold start, and throwOnEmptyMetrics are enabled by the middleware | ||
|
||
const handlerClass = new MyFunctionWithDecorator(); | ||
metrics.addMetric('test-metric', MetricUnits.Count, 10); | ||
|
||
return handlerClass.handler(_event, _context, () => console.log('Lambda invoked!')); | ||
}); | ||
const metricWithItsOwnDimensions = metrics.singleMetric(); | ||
metricWithItsOwnDimensions.addDimension('InnerDimension', 'true'); | ||
metricWithItsOwnDimensions.addMetric('single-metric', MetricUnits.Percent, 50); | ||
|
||
// ### Experiment with Tracer | ||
|
||
handler.before(async (_request) => { | ||
metrics.addMetric('beforeHandlerCalled', MetricUnits.Count, 1); | ||
}); | ||
// Service & Cold Start annotations will be added for you by the decorator/middleware | ||
|
||
handler.after(async (_request) => { | ||
// Won't be flushed since happens after | ||
metrics.addMetric('afterHandlerCalled', MetricUnits.Count, 1); | ||
// These traces will be added to the main segment (## index.handler) | ||
tracer.putAnnotation('awsRequestId', context.awsRequestId); | ||
tracer.putMetadata('eventPayload', event); | ||
|
||
}); | ||
// Create another subsegment & set it as active | ||
const handlerSegment = tracer.getSegment(); // This is the custom segment created by Tracer for you (## index.handler) | ||
ijemmy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const subsegment = handlerSegment.addNewSubsegment('### MySubSegment'); | ||
tracer.setSegment(subsegment); | ||
|
||
handler.onError(async (_request) => { | ||
metrics.addMetric('onErrorHandlerCalled', MetricUnits.Count, 1); | ||
}); | ||
let res; | ||
try { | ||
res = { foo: 'bar' }; | ||
} catch (err) { | ||
throw err; | ||
} finally { | ||
// Close the subsegment you created (### MySubSegment) | ||
subsegment.close(); | ||
// Set back the original segment as active (## index.handler) | ||
tracer.setSegment(handlerSegment); | ||
// The main segment (facade) will be closed for you at the end by the decorator/middleware | ||
} | ||
|
||
return res; | ||
} | ||
|
||
module.exports = { handler }; | ||
// We instrument the handler with the various Middy middlewares | ||
export const handler = middy(lambdaHandler) | ||
.use(captureLambdaHandler(tracer)) | ||
.use(logMetrics(metrics, { | ||
captureColdStartMetric: true, | ||
throwOnEmptyMetrics: true, | ||
defaultDimensions: { environment: 'example', type: 'withDecorator' }, | ||
})) | ||
.use(injectLambdaContext(logger)); |
Uh oh!
There was an error while loading. Please reload this page.