Skip to content
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

docs(all): update & revise docstring examples #1144

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/core/tracer.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ The `Tracer` utility is instantiated outside of the Lambda handler. In doing thi

// You can also pass the parameter in the constructor
// const tracer = new Tracer({
// serviceName: "serverlessAirline"
// serviceName: 'serverlessAirline'
// });
```

Expand Down Expand Up @@ -510,7 +510,7 @@ Tracer exposes a `getRootXrayTraceId()` method that allows you to retrieve the [
return {
statusCode: 500,
body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`,
headers: { "_X_AMZN_TRACE_ID": rootTraceId },
headers: { '_X_AMZN_TRACE_ID': rootTraceId },
};
}
};
Expand Down
70 changes: 48 additions & 22 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,42 +39,26 @@ import type {
*
* @example
* ```typescript
* import { Logger } from "@aws-lambda-powertools/logger";
* import { Logger } from '@aws-lambda-powertools/logger';
*
* // Logger parameters fetched from the environment variables:
* const logger = new Logger();
* ```
*
* ### Functions usage with manual instrumentation
*
* If you prefer to manually instrument your Lambda handler you can use the methods in the Logger class directly.
*
* @example
* ```typescript
* import { Logger } from "@aws-lambda-powertools/logger";
*
* const logger = new Logger();
*
* export const handler = async (_event, context) => {
* logger.addContext(context);
* logger.info("This is an INFO log with some context");
* };
* ```
*
*
* ### Functions usage with middleware
*
* If you use function-based Lambda handlers you can use the [injectLambdaContext()](#injectLambdaContext)
* middy middleware to automatically add context to your Lambda logs.
*
* @example
* ```typescript
* import { Logger, injectLambdaContext } from "@aws-lambda-powertools/logger";
* import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
* import middy from '@middy/core';
*
* const logger = new Logger();
*
* const lambdaHandler = async (_event: any, _context: any) => {
* logger.info("This is an INFO log with some context");
* logger.info('This is an INFO log with some context');
* };
*
* export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));
Expand All @@ -86,22 +70,41 @@ import type {
*
* @example
* ```typescript
* import { Logger } from "@aws-lambda-powertools/logger";
* import { Logger } from '@aws-lambda-powertools/logger';
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
*
* const logger = new Logger();
*
* class Lambda implements LambdaInterface {
*
* // 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`
*
* // Decorate your handler class method
* @logger.injectLambdaContext()
* public async handler(_event: any, _context: any): Promise<void> {
* logger.info("This is an INFO log with some context");
* logger.info('This is an INFO log with some context');
* }
* }
*
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
* ### Functions usage with manual instrumentation
*
* If you prefer to manually instrument your Lambda handler you can use the methods in the Logger class directly.
*
* @example
* ```typescript
* import { Logger } from '@aws-lambda-powertools/logger';
*
* const logger = new Logger();
*
* export const handler = async (_event, context) => {
* logger.addContext(context);
* logger.info('This is an INFO log with some context');
* };
* ```
*
* @class
* @implements {ClassThatLogs}
Expand Down Expand Up @@ -269,9 +272,32 @@ class Logger extends Utility implements ClassThatLogs {
/**
* Method decorator that adds the current Lambda function context as extra
* information in all log items.
*
* The decorator can be used only when attached to a Lambda function handler which
* is written as method of a class, and should be declared just before the handler declaration.
*
* Note: Currently TypeScript only supports decorators on classes and methods. If you are using the
* function syntax, you should use the middleware instead.
*
* @example
* ```typescript
* import { Logger } from '@aws-lambda-powertools/logger';
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
*
* const logger = new Logger();
*
* class Lambda implements LambdaInterface {
* // Decorate your handler class method
* @logger.injectLambdaContext()
* public async handler(_event: any, _context: any): Promise<void> {
* logger.info('This is an INFO log with some context');
* }
* }
*
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
* @see https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators
* @returns {HandlerMethodDecorator}
*/
Expand Down
17 changes: 8 additions & 9 deletions packages/logger/src/middleware/middy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,28 @@ import type middy from '@middy/core';
import { HandlerOptions, LogAttributes } from '../types';

/**
* A middy middleware that adds the current Lambda invocation's context inside all log items.
*
* ## Usage
* A middy middleware that helps emitting CloudWatch EMF metrics in your logs.
*
* 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.
*
* @example
* ```typescript
* import { Logger, injectLambdaContext } from "@aws-lambda-powertools/logger";
*
* import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger';
* import middy from '@middy/core';
*
*
* const logger = new Logger();
*
* const lambdaHandler = async (_event: any, _context: any) => {
* logger.info("This is an INFO log with some context");
* logger.info('This is an INFO log with some context');
* };
*
*
* export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));
* ```
*
* @param {Logger|Logger[]} target - The Tracer instance to use for tracing
* @returns {middy.MiddlewareObj} - The middy middleware object
* @param target - The Logger instance(s) to use for logging
* @param options - (_optional_) Options for the middleware
* @returns - The middy middleware object
*/
const injectLambdaContext = (target: Logger | Logger[], options?: HandlerOptions): middy.MiddlewareObj => {

Expand Down
66 changes: 43 additions & 23 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,35 +30,57 @@ const DEFAULT_NAMESPACE = 'default_namespace';
* * Context manager to create a one off metric with a different dimension
*
* ## Usage
*
* ### Functions usage with middleware
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
*
* @example
* ```typescript
* import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* const lambdaHandler = async (_event: any, _context: any) => {
* ...
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* ```
*
* ### Object oriented way with decorator
*
* 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:
* * create cold start metric
* * capture a `ColdStart` metric
* * flush buffered metrics
* * throw on empty metrics
*
* @example
*
* ```typescript
* import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
* import { Callback, Context } from 'aws-lambda';
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
*
* const metrics = new Metrics({ namespace:'MyService', serviceName:'withDecorator' });
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* export class MyFunctionWithDecorator {
* class Lambda implements LambdaInterface {
*
* // 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`
* // 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`
*
* @metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
* public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<void> {
* // ...
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
* // ...
* public handler(_event: any, _context: any): Promise<void> {
flochaz marked this conversation as resolved.
Show resolved Hide resolved
* // ...
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
* // ...
* }
* }
*
* const handlerClass = new MyFunctionWithDecorator();
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
Expand All @@ -71,7 +93,7 @@ const DEFAULT_NAMESPACE = 'default_namespace';
* ```typescript
* import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'MyService', serviceName: 'MyFunction' });
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* export const handler = async (_event: any, _context: any): Promise<void> => {
* metrics.captureColdStartMetric();
Expand Down Expand Up @@ -164,11 +186,10 @@ class Metrics extends Utility implements MetricsInterface {
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Context } from 'aws-lambda';
*
* const metrics = new Metrics({ namespace:'serverlessAirline', serviceName:'orders' });
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* export const handler = async (event: any, context: Context): Promise<void> => {
* export const handler = async (event: any, _context: any): Promise<void> => {
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
* metrics.captureColdStartMetric();
* };
* ```
Expand Down Expand Up @@ -209,19 +230,19 @@ class Metrics extends Utility implements MetricsInterface {
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Callback, Context } from 'aws-lambda';
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
*
* const metrics = new Metrics({ namespace:'CdkExample', serviceName:'withDecorator' });
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* export class MyFunctionWithDecorator {
* class Lambda implements LambdaInterface {
*
* @metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<any> {
* public handler(_event: any, _context: any): Promise<void> {
* // ...
* }
* }
*
* const handlerClass = new MyFunctionWithDecorator();
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
Expand Down Expand Up @@ -276,7 +297,7 @@ class Metrics extends Utility implements MetricsInterface {
* ```typescript
* import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'CdkExample', serviceName: 'MyFunction' }); // Sets metric namespace, and service as a metric dimension
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
*
* export const handler = async (_event: any, _context: any): Promise<void> => {
* metrics.addMetric('test-metric', MetricUnits.Count, 10);
Expand Down Expand Up @@ -383,11 +404,10 @@ class Metrics extends Utility implements MetricsInterface {
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Context } from 'aws-lambda';
*
* const metrics = new Metrics({ namespace:'serverlessAirline', serviceName:'orders' });
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
*
* export const handler = async (event: any, context: Context): Promise<void> => {
* export const handler = async (_event: any, _context: any): Promise<void> => {
* metrics.throwOnEmptyMetrics();
* metrics.publishStoredMetrics(); // will throw since no metrics added.
* };
Expand Down
27 changes: 27 additions & 0 deletions packages/metrics/src/middleware/middy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,33 @@ import type { Metrics } from '../Metrics';
import type middy from '@middy/core';
import type { ExtraOptions } from '../types';

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
flochaz marked this conversation as resolved.
Show resolved Hide resolved
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
*
* @example
* ```typescript
* import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* const lambdaHandler = async (_event: any, _context: any) => {
* ...
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* ```
*
* @param target - The Metrics instance to use for emitting metrics
* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/
const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): middy.MiddlewareObj => {
const metricsInstances = target instanceof Array ? target : [target];

Expand Down
Loading