Skip to content

Commit 91816ae

Browse files
committed
docs: update & revise docstring examples
1 parent 8b85db1 commit 91816ae

File tree

7 files changed

+149
-72
lines changed

7 files changed

+149
-72
lines changed

Diff for: docs/core/tracer.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ The `Tracer` utility is instantiated outside of the Lambda handler. In doing thi
7575

7676
// You can also pass the parameter in the constructor
7777
// const tracer = new Tracer({
78-
// serviceName: "serverlessAirline"
78+
// serviceName: 'serverlessAirline'
7979
// });
8080
```
8181

@@ -510,7 +510,7 @@ Tracer exposes a `getRootXrayTraceId()` method that allows you to retrieve the [
510510
return {
511511
statusCode: 500,
512512
body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`,
513-
headers: { "_X_AMZN_TRACE_ID": rootTraceId },
513+
headers: { '_X_AMZN_TRACE_ID': rootTraceId },
514514
};
515515
}
516516
};

Diff for: packages/logger/src/Logger.ts

+48-22
Original file line numberDiff line numberDiff line change
@@ -39,42 +39,26 @@ import type {
3939
*
4040
* @example
4141
* ```typescript
42-
* import { Logger } from "@aws-lambda-powertools/logger";
42+
* import { Logger } from '@aws-lambda-powertools/logger';
4343
*
4444
* // Logger parameters fetched from the environment variables:
4545
* const logger = new Logger();
4646
* ```
47-
*
48-
* ### Functions usage with manual instrumentation
49-
*
50-
* If you prefer to manually instrument your Lambda handler you can use the methods in the Logger class directly.
51-
*
52-
* @example
53-
* ```typescript
54-
* import { Logger } from "@aws-lambda-powertools/logger";
55-
*
56-
* const logger = new Logger();
57-
*
58-
* export const handler = async (_event, context) => {
59-
* logger.addContext(context);
60-
* logger.info("This is an INFO log with some context");
61-
* };
62-
* ```
63-
*
47+
*
6448
* ### Functions usage with middleware
6549
*
6650
* If you use function-based Lambda handlers you can use the [injectLambdaContext()](#injectLambdaContext)
6751
* middy middleware to automatically add context to your Lambda logs.
6852
*
6953
* @example
7054
* ```typescript
71-
* import { Logger, injectLambdaContext } from "@aws-lambda-powertools/logger";
55+
* import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
7256
* import middy from '@middy/core';
7357
*
7458
* const logger = new Logger();
7559
*
7660
* const lambdaHandler = async (_event: any, _context: any) => {
77-
* logger.info("This is an INFO log with some context");
61+
* logger.info('This is an INFO log with some context');
7862
* };
7963
*
8064
* export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));
@@ -86,22 +70,41 @@ import type {
8670
*
8771
* @example
8872
* ```typescript
89-
* import { Logger } from "@aws-lambda-powertools/logger";
73+
* import { Logger } from '@aws-lambda-powertools/logger';
9074
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
9175
*
9276
* const logger = new Logger();
9377
*
9478
* class Lambda implements LambdaInterface {
79+
*
80+
* // FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/47679 and might show as *@logger* instead of `@logger.injectLambdaContext`
81+
*
9582
* // Decorate your handler class method
9683
* @logger.injectLambdaContext()
9784
* public async handler(_event: any, _context: any): Promise<void> {
98-
* logger.info("This is an INFO log with some context");
85+
* logger.info('This is an INFO log with some context');
9986
* }
10087
* }
10188
*
10289
* const handlerClass = new Lambda();
10390
* export const handler = handlerClass.handler.bind(handlerClass);
10491
* ```
92+
*
93+
* ### Functions usage with manual instrumentation
94+
*
95+
* If you prefer to manually instrument your Lambda handler you can use the methods in the Logger class directly.
96+
*
97+
* @example
98+
* ```typescript
99+
* import { Logger } from '@aws-lambda-powertools/logger';
100+
*
101+
* const logger = new Logger();
102+
*
103+
* export const handler = async (_event, context) => {
104+
* logger.addContext(context);
105+
* logger.info('This is an INFO log with some context');
106+
* };
107+
* ```
105108
*
106109
* @class
107110
* @implements {ClassThatLogs}
@@ -269,9 +272,32 @@ class Logger extends Utility implements ClassThatLogs {
269272
/**
270273
* Method decorator that adds the current Lambda function context as extra
271274
* information in all log items.
275+
*
272276
* The decorator can be used only when attached to a Lambda function handler which
273277
* is written as method of a class, and should be declared just before the handler declaration.
274278
*
279+
* Note: Currently TypeScript only supports decorators on classes and methods. If you are using the
280+
* function syntax, you should use the middleware instead.
281+
*
282+
* @example
283+
* ```typescript
284+
* import { Logger } from '@aws-lambda-powertools/logger';
285+
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
286+
*
287+
* const logger = new Logger();
288+
*
289+
* class Lambda implements LambdaInterface {
290+
* // Decorate your handler class method
291+
* @logger.injectLambdaContext()
292+
* public async handler(_event: any, _context: any): Promise<void> {
293+
* logger.info('This is an INFO log with some context');
294+
* }
295+
* }
296+
*
297+
* const handlerClass = new Lambda();
298+
* export const handler = handlerClass.handler.bind(handlerClass);
299+
* ```
300+
*
275301
* @see https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators
276302
* @returns {HandlerMethodDecorator}
277303
*/

Diff for: packages/logger/src/middleware/middy.ts

+7-8
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,26 @@ import { HandlerOptions, LogAttributes } from '../types';
55
/**
66
* A middy middleware that adds the current Lambda invocation's context inside all log items.
77
*
8-
* ## Usage
9-
*
8+
* Using this middleware on your handler function will automatically add context information to logs, as well as optionally log the event and clear attributes set during the invocation.
9+
*
1010
* @example
1111
* ```typescript
12-
* import { Logger, injectLambdaContext } from "@aws-lambda-powertools/logger";
13-
*
12+
* import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
1413
* import middy from '@middy/core';
1514
*
1615
*
1716
* const logger = new Logger();
1817
*
1918
* const lambdaHandler = async (_event: any, _context: any) => {
20-
* logger.info("This is an INFO log with some context");
19+
* logger.info('This is an INFO log with some context');
2120
* };
2221
*
23-
*
2422
* export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));
2523
* ```
2624
*
27-
* @param {Logger|Logger[]} target - The Tracer instance to use for tracing
28-
* @returns {middy.MiddlewareObj} - The middy middleware object
25+
* @param target - The Logger instance(s) to use for logging
26+
* @param options - (_optional_) Options for the middleware
27+
* @returns - The middy middleware object
2928
*/
3029
const injectLambdaContext = (target: Logger | Logger[], options?: HandlerOptions): middy.MiddlewareObj => {
3130

Diff for: packages/metrics/src/Metrics.ts

+43-23
Original file line numberDiff line numberDiff line change
@@ -30,35 +30,57 @@ const DEFAULT_NAMESPACE = 'default_namespace';
3030
* * Context manager to create a one off metric with a different dimension
3131
*
3232
* ## Usage
33+
*
34+
* ### Functions usage with middleware
35+
*
36+
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
37+
* Additionally, you can configure the middleware to easily:
38+
* * ensure that at least one metric is emitted before you flush them
39+
* * capture a `ColdStart` a metric
40+
* * set default dimensions for all your metrics
41+
*
42+
* @example
43+
* ```typescript
44+
* import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics';
45+
* import middy from '@middy/core';
46+
*
47+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
48+
*
49+
* const lambdaHandler = async (_event: any, _context: any) => {
50+
* ...
51+
* };
52+
*
53+
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
54+
* ```
3355
*
3456
* ### Object oriented way with decorator
3557
*
3658
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically:
37-
* * create cold start metric
59+
* * capture a `ColdStart` metric
3860
* * flush buffered metrics
3961
* * throw on empty metrics
4062
*
4163
* @example
4264
*
4365
* ```typescript
4466
* import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
45-
* import { Callback, Context } from 'aws-lambda';
67+
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
4668
*
47-
* const metrics = new Metrics({ namespace:'MyService', serviceName:'withDecorator' });
69+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
4870
*
49-
* export class MyFunctionWithDecorator {
71+
* class Lambda implements LambdaInterface {
5072
*
51-
* // FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/39371 and might show as *@metrics* instead of `@metrics.logMetrics`
73+
* // FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/47679 and might show as *@metrics* instead of `@metrics.logMetrics`
5274
*
5375
* @metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
54-
* public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<void> {
55-
* // ...
56-
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
57-
* // ...
76+
* public handler(_event: any, _context: any): Promise<void> {
77+
* // ...
78+
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
79+
* // ...
5880
* }
5981
* }
6082
*
61-
* const handlerClass = new MyFunctionWithDecorator();
83+
* const handlerClass = new Lambda();
6284
* export const handler = handlerClass.handler.bind(handlerClass);
6385
* ```
6486
*
@@ -71,7 +93,7 @@ const DEFAULT_NAMESPACE = 'default_namespace';
7193
* ```typescript
7294
* import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
7395
*
74-
* const metrics = new Metrics({ namespace: 'MyService', serviceName: 'MyFunction' });
96+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
7597
*
7698
* export const handler = async (_event: any, _context: any): Promise<void> => {
7799
* metrics.captureColdStartMetric();
@@ -164,11 +186,10 @@ class Metrics extends Utility implements MetricsInterface {
164186
*
165187
* ```typescript
166188
* import { Metrics } from '@aws-lambda-powertools/metrics';
167-
* import { Context } from 'aws-lambda';
168189
*
169-
* const metrics = new Metrics({ namespace:'serverlessAirline', serviceName:'orders' });
190+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
170191
*
171-
* export const handler = async (event: any, context: Context): Promise<void> => {
192+
* export const handler = async (event: any, _context: any): Promise<void> => {
172193
* metrics.captureColdStartMetric();
173194
* };
174195
* ```
@@ -209,19 +230,19 @@ class Metrics extends Utility implements MetricsInterface {
209230
*
210231
* ```typescript
211232
* import { Metrics } from '@aws-lambda-powertools/metrics';
212-
* import { Callback, Context } from 'aws-lambda';
233+
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
213234
*
214-
* const metrics = new Metrics({ namespace:'CdkExample', serviceName:'withDecorator' });
235+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
215236
*
216-
* export class MyFunctionWithDecorator {
237+
* class Lambda implements LambdaInterface {
217238
*
218239
* @metrics.logMetrics({ captureColdStartMetric: true })
219-
* public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<any> {
240+
* public handler(_event: any, _context: any): Promise<void> {
220241
* // ...
221242
* }
222243
* }
223244
*
224-
* const handlerClass = new MyFunctionWithDecorator();
245+
* const handlerClass = new Lambda();
225246
* export const handler = handlerClass.handler.bind(handlerClass);
226247
* ```
227248
*
@@ -276,7 +297,7 @@ class Metrics extends Utility implements MetricsInterface {
276297
* ```typescript
277298
* import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
278299
*
279-
* const metrics = new Metrics({ namespace: 'CdkExample', serviceName: 'MyFunction' }); // Sets metric namespace, and service as a metric dimension
300+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
280301
*
281302
* export const handler = async (_event: any, _context: any): Promise<void> => {
282303
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
@@ -383,11 +404,10 @@ class Metrics extends Utility implements MetricsInterface {
383404
*
384405
* ```typescript
385406
* import { Metrics } from '@aws-lambda-powertools/metrics';
386-
* import { Context } from 'aws-lambda';
387407
*
388-
* const metrics = new Metrics({ namespace:'serverlessAirline', serviceName:'orders' });
408+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
389409
*
390-
* export const handler = async (event: any, context: Context): Promise<void> => {
410+
* export const handler = async (_event: any, _context: any): Promise<void> => {
391411
* metrics.throwOnEmptyMetrics();
392412
* metrics.publishStoredMetrics(); // will throw since no metrics added.
393413
* };

Diff for: packages/metrics/src/middleware/middy.ts

+27
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,33 @@ import type { Metrics } from '../Metrics';
22
import type middy from '@middy/core';
33
import type { ExtraOptions } from '../types';
44

5+
/**
6+
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
7+
*
8+
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
9+
* Additionally, you can configure the middleware to easily:
10+
* * ensure that at least one metric is emitted before you flush them
11+
* * capture a `ColdStart` a metric
12+
* * set default dimensions for all your metrics
13+
*
14+
* @example
15+
* ```typescript
16+
* import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics';
17+
* import middy from '@middy/core';
18+
*
19+
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
20+
*
21+
* const lambdaHandler = async (_event: any, _context: any) => {
22+
* ...
23+
* };
24+
*
25+
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
26+
* ```
27+
*
28+
* @param target - The Metrics instance to use for emitting metrics
29+
* @param options - (_optional_) Options for the middleware
30+
* @returns middleware - The middy middleware object
31+
*/
532
const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): middy.MiddlewareObj => {
633
const metricsInstances = target instanceof Array ? target : [target];
734

0 commit comments

Comments
 (0)