From 5dd37ba25646325fb4b7c8a7dfc235cf758e351d Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Tue, 30 Jan 2024 17:29:57 +0100 Subject: [PATCH 01/22] docs(maintenance): create upgrade guide --- docs/upgrade.md | 189 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 187 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 88a94294d5..a74afd70a2 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -3,5 +3,190 @@ title: Upgrade guide description: Guide to update between major Powertools for AWS Lambda (TypeScript) versions --- -!!! warning - This guide is a work in progress. We'll update it as we get closer to the 2.0 release. If you have any questions, or want to follow the progress, please join the discussion on the [GitHub issue](https://github.com/aws-powertools/powertools-lambda-typescript/issues/1714). \ No newline at end of file +## Migrate from v1 to v2 + +We've made targeted breaking changes to make your transition to v2 as smooth as possible while still providing you with the most up-to-date features and patterns. This guide will help you migrate your existing codebase to v2. + +### Quick summary + +| Area | Change | Code change required | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | +| **ES Modules support** | TBD | - | +| **Middy.js middleware imports** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | +| **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | +| **Logger - log sampling** | Changed implementation of [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | +| **Logger - Custom Log Formatter** | Updated [custom log formatter](#custom-log-formatter) to include additional persistent attributes along with standard structured keys. | Yes | +| **Logger & Tracer - helper functions** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | + +### First steps + +Before you start, we suggest making a copy of your current working project or create a new git branch. + +1. Upgrade Node.js to v16 or higher, Node.js v20 is recommended. +2. Ensure that you have the latest Powertools for AWS Lambda (TypeScript) version via [Lambda Layer](./index.md#lambda-layer) or npm. +3. Review the following sections to confirm whether they apply to your codebase. + +## ES Modules support + +TBD + +## Scoped imports + +### Middy.js middleware imports + +Code changes are required only if you're using Middy.js middlewares, however this update benefits especially those who are **not** using Middy.js middlewares due to less code being imported and bundled in your Lambda function. + +In v1, you could importing Middy.js middlewares in your codebase directly from the default export of a package. For example, to import the `injectLambdaContext` middleware for Logger, you would import it from `@aws-lambda-powertools/logger`. + +With v2, we've added support for subpath exports. This means that you can now import Middy.js middlewares directly from a well-known path, i.e. `@aws-lambda-powertools/logger/middleware`. This allows you to import the middleware only when you need it, instead of requiring it and having it bundled in your Lambda function when you import the package. + +### Types imports + +In v1, importing TypeScript types in your codebase required you to be aware of the underlying directory structure of the Powertools for AWS Lambda (TypeScript) package. For example, to import a type from the `@aws-lambda-powertools/logger` package, you would need to import it from `@aws-lambda-powertools/logger/lib/types`. + +Starting with v2, we've added support for subpath exports. This means that you can now import types directly from a well-known path, i.e. `@aws-lambda-powertools/logger/types`. This makes it easier and cleaner to import types in your codebase and removes the likelihood of breaking changes in the future. + +## Logger + +### Log sampling + +This only applies if you're using the [log sampling](./core/logger.md#sampling-logs) feature in your codebase. + +In v1, the `sampleRateValue` attribute could be set to a value between 0 and 1 when instantiating the `Logger` class. This value was used to determine the percentage of requests that would print logs at any log level regardless of the log level set in the `Logger` class. + +For example, by setting the sample rate to 0.5 together with log level `ERROR`, roughly 50% of your Lambda invocations would print all the log items, including the `debug`, `info`, and `warn` ones. + +```typescript +import { Logger } from '@aws-lambda-powertools/logger'; + +const logger = new Logger({ + logLevel: 'ERROR', + sampleRateValue: 0.5, +}); + +export const handler = async () => { + // This log item (equal to log level 'ERROR') will be printed to standard output + // in all Lambda invocations + logger.error('This is an ERROR log'); + + // These log items (below the log level 'ERROR') have ~50% chance + // of being printed in a Lambda invocation + logger.debug('This is a DEBUG log that has 50% chance of being printed'); + logger.info('This is an INFO log that has 50% chance of being printed'); + logger.warn('This is a WARN log that has 50% chance of being printed'); +}; +``` + +In v2, the `sampleRateValue` attribute is now used to determine the approximate percentage of requests that will have their log level switched to `DEBUG`. This means that the log level set in the `Logger` class will be used for all Lambda invocations, but for a percentage of them, the log level will be switched to `DEBUG` and all log items will be printed to standard output. + +With this new behavior, you should see roughly the same number of log items printed to standard output as in v1, however, the implementation and logic is now in line with other runtimes of Powertools for AWS Lambda like Python, Java, and .NET. + +### Custom log formatter + +This only applies if you're using [a custom log formatter](./core/logger.md#custom-log-formatter-bring-your-own-formatter) to customize the log output. + +Previously, the `formatAttributes` method was called with a single argument `attributes` of type `UnformattedAttributes`. This object contained all the [standard structured keys](./core/logger.md#standard-structured-keys) and values managed by Powertools for AWS Lambda (TypeScript). The method returned a plain object with the keys and values you wanted to include in the log output. + +```typescript hl_lines="5 8" +import { LogFormatter } from '@aws-lambda-powertools/logger'; +import { + LogAttributes, + UnformattedAttributes, +} from '@aws-lambda-powertools/logger/lib/types'; + +class MyCompanyLogFormatter extends LogFormatter { + public formatAttributes(attributes: UnformattedAttributes): LogAttributes { + return { + message: attributes.message, + service: attributes.serviceName, + environment: attributes.environment, + awsRegion: attributes.awsRegion, + correlationIds: { + awsRequestId: attributes.lambdaContext?.awsRequestId, + xRayTraceId: attributes.xRayTraceId, + }, + lambdaFunction: { + name: attributes.lambdaContext?.functionName, + arn: attributes.lambdaContext?.invokedFunctionArn, + memoryLimitInMB: attributes.lambdaContext?.memoryLimitInMB, + version: attributes.lambdaContext?.functionVersion, + coldStart: attributes.lambdaContext?.coldStart, + }, + logLevel: attributes.logLevel, + timestamp: this.formatTimestamp(attributes.timestamp), + logger: { + sampleRateValue: attributes.sampleRateValue, + }, + }; + } +} + +export { MyCompanyLogFormatter }; +``` + +In v2, the `formatAttributes` method is instead called with two arguments `attributes` and `additionalLogAttributes`. The `attributes` argument is the same as in v1, but the `additionalLogAttributes` argument is a plain object containing any [additional attributes you might have added](./core/logger.md#appending-persistent-additional-log-keys-and-values) to your logger. The method returns a `LogItem` object that contains all the attributes you want to include in the log output. + +```typescript hl_lines="1-2 5-8" +import { LogFormatter, LogItem } from '@aws-lambda-powertools/logger'; +import type { LogAttributes, UnformattedAttributes } from '@aws-lambda-powertools/logger/types'; + +class MyCompanyLogFormatter extends LogFormatter { + public formatAttributes( + attributes: UnformattedAttributes, + additionalLogAttributes: LogAttributes + ): LogItem { + const baseAttributes = { + message: attributes.message, + service: attributes.serviceName, + environment: attributes.environment, + awsRegion: attributes.awsRegion, + correlationIds: { + awsRequestId: attributes.lambdaContext?.awsRequestId, + xRayTraceId: attributes.xRayTraceId, + }, + lambdaFunction: { + name: attributes.lambdaContext?.functionName, + arn: attributes.lambdaContext?.invokedFunctionArn, + memoryLimitInMB: attributes.lambdaContext?.memoryLimitInMB, + version: attributes.lambdaContext?.functionVersion, + coldStart: attributes.lambdaContext?.coldStart, + }, + logLevel: attributes.logLevel, + timestamp: this.formatTimestamp(attributes.timestamp), + logger: { + sampleRateValue: attributes.sampleRateValue, + }, + }; + // Create a new LogItem with the base attributes + const logItem = new LogItem({ attributes: baseAttributes }); + // Merge additional attributes + logItem.addAttributes(additionalLogAttributes); + + return logItem; + } +} + +export { MyCompanyLogFormatter }; +``` + +## Helper functions + +We removed the deprecated `createLogger` and `createTracer` heper functions. + +```typescript +import { createLogger } from '@aws-lambda-powertools/logger'; +import { createTracer } from '@aws-lambda-powertools/tracer'; + +const logger = createLogger({ logLevel: 'info' }); +const tracer = createTracer({ serviceName: 'my-service' }); +``` + +You can migrate to instantiating the `Logger` and `Tracer` classes directly with no additional changes. + +```typescript +import { Logger } from '@aws-lambda-powertools/logger'; +import { Tracer } from '@aws-lambda-powertools/tracer'; + +const logger = new Logger({ logLevel: 'info' }); +const tracer = new Tracer({ serviceName: 'my-service' }); +``` From 8ab8730120e87f6fb2bfb5646c5583c6a5b3576f Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Wed, 31 Jan 2024 17:59:48 +0100 Subject: [PATCH 02/22] docs: added section about esm --- docs/upgrade.md | 75 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index a74afd70a2..bed58faa87 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -11,7 +11,7 @@ We've made targeted breaking changes to make your transition to v2 as smooth as | Area | Change | Code change required | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | -| **ES Modules support** | TBD | - | +| **ES Modules support** | Added ES Modules support via dual CommonJS and ES Module bundling, this enables top-level `await` and tree-shaking. | No | | **Middy.js middleware imports** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger - log sampling** | Changed implementation of [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | @@ -28,7 +28,78 @@ Before you start, we suggest making a copy of your current working project or cr ## ES Modules support -TBD +Starting with v2, Powertools for AWS Lambda (TypeScript) supports ES Modules. This means that you can now import the package using the `import` syntax instead of the `require` syntax. This is especially useful if you want to leverage features like top-level `await` in your Lambda function to run asynchronous code during the initialization phase. + +```typescript +import { getSecret } from '@aws-lambda-powertools/parameters/secrets'; + +// This code will run during the initialization phase of your Lambda function +const myApiKey = await getSecret('my-api-key', { transform: 'json' }); + +export const handler = async () => { + // ... +}; +``` + +With this change, you can also apply tree-shaking to your function bundle to reduce its size. As part of this release we have made changes to the package and its exports to better support this feature, and we remain committed to improving this in the future based on your feedback. + +While we recommend using ES Modules, we understand that this change might not be possible for everyone. If you're unable to use ES Modules, you can continue to use the `require` syntax to import the package. Powertools for AWS Lambda (TypeScript) will continue to support this syntax by shipping CommonJS modules alongside ES Modules. + +In some cases, even when opting for ES Modules, you might still need to use the `require` syntax to import a package. For example, if you're using a package that doesn't support ES Modules, or if one of your transitive dependencies is using the `require` syntax like it's the case for `@aws-lambda-powertools/tracer` which relies on the AWS X-Ray SDK for Node.js. In these cases, you can still use ES Modules for the rest of your codebase and set a special build flag to tell your bundler to inject a banner at the top of the file to use the `require` syntax for the specific package. + +=== "With AWS CDK" + + ```typescript hl_lines="15 20-21" + import { Stack, type StackProps } from 'aws-cdk-lib'; + import { Construct } from 'constructs'; + import { NodejsFunction, OutputFormat } from 'aws-cdk-lib/aws-lambda-nodejs'; + import { Runtime } from 'aws-cdk-lib/aws-lambda'; + + export class MyStack extends Stack { + public constructor(scope: Construct, id: string, props?: StackProps) { + super(scope, id, props); + + const handler = new NodejsFunction(this, 'helloWorldFunction', { + runtime: Runtime.NODEJS_20_X, + handler: 'handler', + entry: 'src/index.ts', + bundling: { + format: OutputFormat.ESM, + minify: true, + esbuildArgs: { + "--tree-shaking": "true", + }, + banner: + "import { createRequire } from 'module';const require = createRequire(import.meta.url);", + }, + }); + } + } + ``` + +=== "With AWS SAM" + + ```yaml hl_lines="14 17-18" + Transform: AWS::Serverless-2016-10-31 + Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + Runtime: nodejs20.x + Handler: src/index.handler + Metadata: + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: 'ES2020' + Sourcemap: true + Format: esm + EntryPoints: + - src/index.ts + Banner: + js: "import { createRequire } from 'module';const require = createRequire(import.meta.url);" + + ``` ## Scoped imports From 870567a6bc42ed2ef2960c6da86b19ee602c2b14 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Mon, 5 Feb 2024 13:46:56 +0100 Subject: [PATCH 03/22] docs(maintenance): feedback --- docs/upgrade.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index bed58faa87..aa8e1bc495 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -5,13 +5,15 @@ description: Guide to update between major Powertools for AWS Lambda (TypeScript ## Migrate from v1 to v2 -We've made targeted breaking changes to make your transition to v2 as smooth as possible while still providing you with the most up-to-date features and patterns. This guide will help you migrate your existing codebase to v2. +To make your transition to v2 as smooth as possible while still providing you with the most up-to-date features and patterns we have made targeted breaking changes to some of the utilities. This guide will help you migrate your existing codebase to v2. ### Quick summary +Below a list of the main changes introduced in v2, review the sections below for more details and code examples for the changes that apply to your codebase. + | Area | Change | Code change required | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | -| **ES Modules support** | Added ES Modules support via dual CommonJS and ES Module bundling, this enables top-level `await` and tree-shaking. | No | +| **ES Modules support** | Added ES Modules support via dual CommonJS and ES Module bundling, this enables top-level `await` and tree-shaking. | - | | **Middy.js middleware imports** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger - log sampling** | Changed implementation of [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | From ae98c464833cd567276d5c45965047a6faa4062e Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:25:41 +0100 Subject: [PATCH 04/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index aa8e1bc495..0b4af9aa3e 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -5,11 +5,11 @@ description: Guide to update between major Powertools for AWS Lambda (TypeScript ## Migrate from v1 to v2 -To make your transition to v2 as smooth as possible while still providing you with the most up-to-date features and patterns we have made targeted breaking changes to some of the utilities. This guide will help you migrate your existing codebase to v2. + +V2 is focused on official support for ESM (ECMAScript modules). We've made other minimal breaking changes to make your transition to v2 as smooth as possible. ### Quick summary -Below a list of the main changes introduced in v2, review the sections below for more details and code examples for the changes that apply to your codebase. | Area | Change | Code change required | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | From e585fa4c706e25c2becce90d2187e1439afed026 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:25:55 +0100 Subject: [PATCH 05/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 0b4af9aa3e..5f4c1841fb 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -13,7 +13,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | Area | Change | Code change required | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | -| **ES Modules support** | Added ES Modules support via dual CommonJS and ES Module bundling, this enables top-level `await` and tree-shaking. | - | +| **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | | **Middy.js middleware imports** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger - log sampling** | Changed implementation of [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | From 37abe5ea6c573427cd1a31c769b85e9deb7f8141 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:26:18 +0100 Subject: [PATCH 06/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 5f4c1841fb..5bc98bd7b1 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -14,7 +14,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | Area | Change | Code change required | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | | **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | -| **Middy.js middleware imports** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | +| **Middy.js ** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger - log sampling** | Changed implementation of [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | | **Logger - Custom Log Formatter** | Updated [custom log formatter](#custom-log-formatter) to include additional persistent attributes along with standard structured keys. | Yes | From bf79b3bde4863559a39a9a91830351203f765fd1 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:26:34 +0100 Subject: [PATCH 07/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 5bc98bd7b1..9e2f14c57c 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -16,7 +16,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | | **Middy.js ** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | -| **Logger - log sampling** | Changed implementation of [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | +| **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | | **Logger - Custom Log Formatter** | Updated [custom log formatter](#custom-log-formatter) to include additional persistent attributes along with standard structured keys. | Yes | | **Logger & Tracer - helper functions** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | From 5a62ace158e59e93310c6b25f653f38b1acc5887 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:26:45 +0100 Subject: [PATCH 08/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 9e2f14c57c..c638d3d43e 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -17,7 +17,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | **Middy.js ** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | -| **Logger - Custom Log Formatter** | Updated [custom log formatter](#custom-log-formatter) to include additional persistent attributes along with standard structured keys. | Yes | +| **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | | **Logger & Tracer - helper functions** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | ### First steps From 9a501338fd876cb53db3608189a35503e99a7cd7 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:26:58 +0100 Subject: [PATCH 09/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index c638d3d43e..64a9fe5a7c 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -28,7 +28,7 @@ Before you start, we suggest making a copy of your current working project or cr 2. Ensure that you have the latest Powertools for AWS Lambda (TypeScript) version via [Lambda Layer](./index.md#lambda-layer) or npm. 3. Review the following sections to confirm whether they apply to your codebase. -## ES Modules support +## ESM support Starting with v2, Powertools for AWS Lambda (TypeScript) supports ES Modules. This means that you can now import the package using the `import` syntax instead of the `require` syntax. This is especially useful if you want to leverage features like top-level `await` in your Lambda function to run asynchronous code during the initialization phase. From 0998e294bbe5a2b6ff51249697388c3671a7922b Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:27:24 +0100 Subject: [PATCH 10/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 160 +++++++++++++++++++++++++----------------------- 1 file changed, 85 insertions(+), 75 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 64a9fe5a7c..0544737c67 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -158,89 +158,99 @@ With this new behavior, you should see roughly the same number of log items prin This only applies if you're using [a custom log formatter](./core/logger.md#custom-log-formatter-bring-your-own-formatter) to customize the log output. -Previously, the `formatAttributes` method was called with a single argument `attributes` of type `UnformattedAttributes`. This object contained all the [standard structured keys](./core/logger.md#standard-structured-keys) and values managed by Powertools for AWS Lambda (TypeScript). The method returned a plain object with the keys and values you wanted to include in the log output. - -```typescript hl_lines="5 8" -import { LogFormatter } from '@aws-lambda-powertools/logger'; -import { - LogAttributes, - UnformattedAttributes, -} from '@aws-lambda-powertools/logger/lib/types'; - -class MyCompanyLogFormatter extends LogFormatter { - public formatAttributes(attributes: UnformattedAttributes): LogAttributes { - return { - message: attributes.message, - service: attributes.serviceName, - environment: attributes.environment, - awsRegion: attributes.awsRegion, - correlationIds: { - awsRequestId: attributes.lambdaContext?.awsRequestId, - xRayTraceId: attributes.xRayTraceId, - }, - lambdaFunction: { - name: attributes.lambdaContext?.functionName, - arn: attributes.lambdaContext?.invokedFunctionArn, - memoryLimitInMB: attributes.lambdaContext?.memoryLimitInMB, - version: attributes.lambdaContext?.functionVersion, - coldStart: attributes.lambdaContext?.coldStart, - }, - logLevel: attributes.logLevel, - timestamp: this.formatTimestamp(attributes.timestamp), - logger: { - sampleRateValue: attributes.sampleRateValue, - }, - }; - } -} - -export { MyCompanyLogFormatter }; -``` - -In v2, the `formatAttributes` method is instead called with two arguments `attributes` and `additionalLogAttributes`. The `attributes` argument is the same as in v1, but the `additionalLogAttributes` argument is a plain object containing any [additional attributes you might have added](./core/logger.md#appending-persistent-additional-log-keys-and-values) to your logger. The method returns a `LogItem` object that contains all the attributes you want to include in the log output. - -```typescript hl_lines="1-2 5-8" -import { LogFormatter, LogItem } from '@aws-lambda-powertools/logger'; -import type { LogAttributes, UnformattedAttributes } from '@aws-lambda-powertools/logger/types'; - -class MyCompanyLogFormatter extends LogFormatter { - public formatAttributes( - attributes: UnformattedAttributes, - additionalLogAttributes: LogAttributes - ): LogItem { - const baseAttributes = { - message: attributes.message, - service: attributes.serviceName, - environment: attributes.environment, - awsRegion: attributes.awsRegion, - correlationIds: { +In v1, `Logger` combined both [standard]((./core/logger.md#standard-structured-keys)) and [custom keys](./core/logger.md#appending-persistent-additional-log-keys-and-values) as a single argument, _e.g., `formatAttributes(attributes: UnformattedAttributes)`_. It expected a plain object with keys and values you wanted in the final log output. + +In v2, you have more control over **standard** (`attributes`) and **custom keys** (`additionalLogAttributes`) in the `formatAttributes` method. Also, you now return a `LogItem` object to increase type safety when defining the final log output. + +=== "Before" + + ```typescript hl_lines="5 8" + import { LogFormatter } from '@aws-lambda-powertools/logger'; + import { + LogAttributes, + UnformattedAttributes, + } from '@aws-lambda-powertools/logger/lib/types'; + + class MyCompanyLogFormatter extends LogFormatter { + public formatAttributes(attributes: UnformattedAttributes): LogAttributes { + return { + message: attributes.message, + service: attributes.serviceName, + environment: attributes.environment, + awsRegion: attributes.awsRegion, + correlationIds: { awsRequestId: attributes.lambdaContext?.awsRequestId, xRayTraceId: attributes.xRayTraceId, - }, - lambdaFunction: { + }, + lambdaFunction: { name: attributes.lambdaContext?.functionName, arn: attributes.lambdaContext?.invokedFunctionArn, memoryLimitInMB: attributes.lambdaContext?.memoryLimitInMB, version: attributes.lambdaContext?.functionVersion, coldStart: attributes.lambdaContext?.coldStart, - }, - logLevel: attributes.logLevel, - timestamp: this.formatTimestamp(attributes.timestamp), - logger: { + }, + logLevel: attributes.logLevel, + timestamp: this.formatTimestamp(attributes.timestamp), + logger: { sampleRateValue: attributes.sampleRateValue, - }, - }; - // Create a new LogItem with the base attributes - const logItem = new LogItem({ attributes: baseAttributes }); - // Merge additional attributes - logItem.addAttributes(additionalLogAttributes); - - return logItem; - } -} - -export { MyCompanyLogFormatter }; -``` + }, + }; + } + } + + export { MyCompanyLogFormatter }; + ``` + +=== "After" + + ```typescript hl_lines="1-2 5-8" + import { LogFormatter, LogItem } from '@aws-lambda-powertools/logger'; + import type { LogAttributes, UnformattedAttributes } from '@aws-lambda-powertools/logger/types'; + + class MyCompanyLogFormatter extends LogFormatter { + public formatAttributes( + attributes: UnformattedAttributes, + additionalLogAttributes: LogAttributes // (1)! + ): LogItem { // (2)! + const baseAttributes = { + message: attributes.message, + service: attributes.serviceName, + environment: attributes.environment, + awsRegion: attributes.awsRegion, + correlationIds: { + awsRequestId: attributes.lambdaContext?.awsRequestId, + xRayTraceId: attributes.xRayTraceId, + }, + lambdaFunction: { + name: attributes.lambdaContext?.functionName, + arn: attributes.lambdaContext?.invokedFunctionArn, + memoryLimitInMB: attributes.lambdaContext?.memoryLimitInMB, + version: attributes.lambdaContext?.functionVersion, + coldStart: attributes.lambdaContext?.coldStart, + }, + logLevel: attributes.logLevel, + timestamp: this.formatTimestamp(attributes.timestamp), + logger: { + sampleRateValue: attributes.sampleRateValue, + }, + }; + + // Create a new LogItem with the base attributes + const logItem = new LogItem({ attributes: baseAttributes }); + + // Merge additional attributes + logItem.addAttributes(additionalLogAttributes); // (3)! + + return logItem; + } + } + + export { MyCompanyLogFormatter }; + ``` + + 1. This new argument contains all [your custom keys](./core/logger.md#appending-persistent-additional-log-keys-and-values). + 2. `LogItem` is the new return object instead of a plain object. + 3. If you prefer adding at the initialization, use:

**`LogItem({persistentAttributes: additionalLogAttributes, attributes: baseAttributes})`** ## Helper functions From 5475d40a4591da8a8b49482f6ccba8d4d7c85d3e Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:28:02 +0100 Subject: [PATCH 11/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 0544737c67..4dd66f1ac8 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -18,7 +18,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | | **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | -| **Logger & Tracer - helper functions** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | +| **Logger and Tracer** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | ### First steps From d7be5536fa4af36b15a055940ef23dc4da72d1f6 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:28:45 +0100 Subject: [PATCH 12/22] Update docs/upgrade.md Co-authored-by: Heitor Lessa --- docs/upgrade.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 4dd66f1ac8..0a787ae73b 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -30,7 +30,9 @@ Before you start, we suggest making a copy of your current working project or cr ## ESM support -Starting with v2, Powertools for AWS Lambda (TypeScript) supports ES Modules. This means that you can now import the package using the `import` syntax instead of the `require` syntax. This is especially useful if you want to leverage features like top-level `await` in your Lambda function to run asynchronous code during the initialization phase. +With support for ES Modules in v2, you can now use `import` instead of `require` syntax. + +This is especially useful when you want to run asynchronous code during the initialization phase by using top-level `await`. ```typescript import { getSecret } from '@aws-lambda-powertools/parameters/secrets'; From cdc44e28e2871dba3cde55731ada9c40725bfba5 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:30:39 +0100 Subject: [PATCH 13/22] Apply suggestions from code review Co-authored-by: Heitor Lessa --- docs/upgrade.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 0a787ae73b..ddfe7a867f 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -34,18 +34,18 @@ With support for ES Modules in v2, you can now use `import` instead of `require` This is especially useful when you want to run asynchronous code during the initialization phase by using top-level `await`. -```typescript +```typescript title="top-level await example in v2" import { getSecret } from '@aws-lambda-powertools/parameters/secrets'; // This code will run during the initialization phase of your Lambda function const myApiKey = await getSecret('my-api-key', { transform: 'json' }); -export const handler = async () => { +export const handler = async (_event, _context) => { // ... }; ``` -With this change, you can also apply tree-shaking to your function bundle to reduce its size. As part of this release we have made changes to the package and its exports to better support this feature, and we remain committed to improving this in the future based on your feedback. +In v2, we improved tree-shaking support to help you reduce your function bundle size. We would love to hear your feedback on further improvements we could make. While we recommend using ES Modules, we understand that this change might not be possible for everyone. If you're unable to use ES Modules, you can continue to use the `require` syntax to import the package. Powertools for AWS Lambda (TypeScript) will continue to support this syntax by shipping CommonJS modules alongside ES Modules. From aa418fc4d6df3095d22813ef77b4830b141464d6 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:30:56 +0100 Subject: [PATCH 14/22] Apply suggestions from code review Co-authored-by: Heitor Lessa --- docs/upgrade.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index ddfe7a867f..af2881e8c2 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -74,12 +74,14 @@ In some cases, even when opting for ES Modules, you might still need to use the "--tree-shaking": "true", }, banner: - "import { createRequire } from 'module';const require = createRequire(import.meta.url);", + "import { createRequire } from 'module';const require = createRequire(import.meta.url);", // (1)! }, }); } } ``` + + 1. `esbuild` will include this arbitrary code at the top of your bundle to maximize CommonJS compatibility _(`require` keyword)_. === "With AWS SAM" @@ -101,19 +103,22 @@ In some cases, even when opting for ES Modules, you might still need to use the EntryPoints: - src/index.ts Banner: - js: "import { createRequire } from 'module';const require = createRequire(import.meta.url);" + js: "import { createRequire } from 'module';const require = createRequire(import.meta.url);" # (1)! ``` + 1. `esbuild` will include this arbitrary code at the top of your bundle to maximize CommonJS compatibility _(`require` keyword)_. + ## Scoped imports ### Middy.js middleware imports -Code changes are required only if you're using Middy.js middlewares, however this update benefits especially those who are **not** using Middy.js middlewares due to less code being imported and bundled in your Lambda function. +???+ note "Disregard if you are not using Middy.js middlewares." + In v2, we've added support for subpath exports. This means if you don't import Middy.js middlewares, you will benefit from a smaller bundle size. -In v1, you could importing Middy.js middlewares in your codebase directly from the default export of a package. For example, to import the `injectLambdaContext` middleware for Logger, you would import it from `@aws-lambda-powertools/logger`. +In v1, you could import Middy.js middlewares from the default export of a package _(e.g., `logger`)_. For example, you'd import `injectLambdaContext` Logger middleware from `@aws-lambda-powertools/logger`. -With v2, we've added support for subpath exports. This means that you can now import Middy.js middlewares directly from a well-known path, i.e. `@aws-lambda-powertools/logger/middleware`. This allows you to import the middleware only when you need it, instead of requiring it and having it bundled in your Lambda function when you import the package. +In v2, you can now import only the Middy.js middlewares you want to use from a subpath export, _e.g., `@aws-lambda-powertools/logger/middleware`_, leading to a smaller bundle size. ### Types imports From 9fc92c943b3edbb6e2d32443ddba38e7796f4e7c Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:31:16 +0100 Subject: [PATCH 15/22] Apply suggestions from code review Co-authored-by: Heitor Lessa --- docs/upgrade.md | 40 +++++++++++----------------------------- 1 file changed, 11 insertions(+), 29 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index af2881e8c2..db99f7aab1 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -122,48 +122,30 @@ In v2, you can now import only the Middy.js middlewares you want to use from a s ### Types imports -In v1, importing TypeScript types in your codebase required you to be aware of the underlying directory structure of the Powertools for AWS Lambda (TypeScript) package. For example, to import a type from the `@aws-lambda-powertools/logger` package, you would need to import it from `@aws-lambda-powertools/logger/lib/types`. +In v1, you could import package types from each package under `/lib`, for example `@aws-lambda-powertools/logger/lib/types`. -Starting with v2, we've added support for subpath exports. This means that you can now import types directly from a well-known path, i.e. `@aws-lambda-powertools/logger/types`. This makes it easier and cleaner to import types in your codebase and removes the likelihood of breaking changes in the future. +In v2, you can now directly import from the `types` subpath export, e.g., `@aws-lambda-powertools/logger/types`. This will optimize your bundle size, standardize types import across packages, future-proofing growth. ## Logger ### Log sampling -This only applies if you're using the [log sampling](./core/logger.md#sampling-logs) feature in your codebase. +!!! note "Disregard if you are not using the [log sampling feature](./core/logger.md#sampling-logs)." -In v1, the `sampleRateValue` attribute could be set to a value between 0 and 1 when instantiating the `Logger` class. This value was used to determine the percentage of requests that would print logs at any log level regardless of the log level set in the `Logger` class. +In v1, log sampling implementation was inconsistent from other Powertools for AWS Lambda languages _(Python, .NET, and Java)_. -For example, by setting the sample rate to 0.5 together with log level `ERROR`, roughly 50% of your Lambda invocations would print all the log items, including the `debug`, `info`, and `warn` ones. +In v2, we changed these behaviors for consistency across languages: -```typescript -import { Logger } from '@aws-lambda-powertools/logger'; - -const logger = new Logger({ - logLevel: 'ERROR', - sampleRateValue: 0.5, -}); - -export const handler = async () => { - // This log item (equal to log level 'ERROR') will be printed to standard output - // in all Lambda invocations - logger.error('This is an ERROR log'); - - // These log items (below the log level 'ERROR') have ~50% chance - // of being printed in a Lambda invocation - logger.debug('This is a DEBUG log that has 50% chance of being printed'); - logger.info('This is an INFO log that has 50% chance of being printed'); - logger.warn('This is a WARN log that has 50% chance of being printed'); -}; -``` - -In v2, the `sampleRateValue` attribute is now used to determine the approximate percentage of requests that will have their log level switched to `DEBUG`. This means that the log level set in the `Logger` class will be used for all Lambda invocations, but for a percentage of them, the log level will be switched to `DEBUG` and all log items will be printed to standard output. +| Behavior | v1 | v2 | +| ----------------------- | ------------------------------------------------------------ | --------------------------------------------- | +| Log Level | Log level remains unchanged but any log statement is printed | Log level changes to `DEBUG` | +| Log sampling indication | No indication | Debug message indicates sampling is in effect | -With this new behavior, you should see roughly the same number of log items printed to standard output as in v1, however, the implementation and logic is now in line with other runtimes of Powertools for AWS Lambda like Python, Java, and .NET. +Logger `sampleRateValue` **continues** to determine the percentage of concurrent/cold start invocations that logs will be sampled, _e.g., log level set to `DEBUG`_. ### Custom log formatter -This only applies if you're using [a custom log formatter](./core/logger.md#custom-log-formatter-bring-your-own-formatter) to customize the log output. +!!! note "Disregard if you are not customizing log output with a [custom log formatter](./core/logger.md#custom-log-formatter-bring-your-own-formatter)." In v1, `Logger` combined both [standard]((./core/logger.md#standard-structured-keys)) and [custom keys](./core/logger.md#appending-persistent-additional-log-keys-and-values) as a single argument, _e.g., `formatAttributes(attributes: UnformattedAttributes)`_. It expected a plain object with keys and values you wanted in the final log output. From d0aa19b1c6bced39f860fa6368d7183afcd4617a Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:35:34 +0100 Subject: [PATCH 16/22] chore: formatting --- docs/upgrade.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index db99f7aab1..446a2d4c28 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -11,14 +11,14 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other ### Quick summary -| Area | Change | Code change required | -| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | -| **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | -| **Middy.js ** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | -| **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | -| **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | -| **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | -| **Logger and Tracer** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | +| Area | Change | Code change required | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------- | +| **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | +| **Middy.js ** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | +| **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | +| **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | +| **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | +| **Logger and Tracer** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | ### First steps @@ -40,7 +40,7 @@ import { getSecret } from '@aws-lambda-powertools/parameters/secrets'; // This code will run during the initialization phase of your Lambda function const myApiKey = await getSecret('my-api-key', { transform: 'json' }); -export const handler = async (_event, _context) => { +export const handler = async (_event: unknown, _context: unknown) => { // ... }; ``` From 8968b04dd42a644328d74c9c3e0612f6f4388e44 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:35:45 +0100 Subject: [PATCH 17/22] chore: added before & after Middy --- docs/upgrade.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/upgrade.md b/docs/upgrade.md index 446a2d4c28..708e170089 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -120,6 +120,25 @@ In v1, you could import Middy.js middlewares from the default export of a packag In v2, you can now import only the Middy.js middlewares you want to use from a subpath export, _e.g., `@aws-lambda-powertools/logger/middleware`_, leading to a smaller bundle size. +=== "Before" + + ```typescript + import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger'; + import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer'; + import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics'; + ``` + +=== "After" + + ```typescript hl_lines="2 4 6" + import { Logger } from '@aws-lambda-powertools/logger'; + import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware'; + import { Tracer } from '@aws-lambda-powertools/tracer'; + import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware'; + import { Metrics } from '@aws-lambda-powertools/metrics'; + import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'; + ``` + ### Types imports In v1, you could import package types from each package under `/lib`, for example `@aws-lambda-powertools/logger/lib/types`. From 0518619a6f5cfe462026c764d645391cc542c7fb Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:41:56 +0100 Subject: [PATCH 18/22] chore: added banner at the top --- docs/upgrade.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 708e170089..ce60bcf26f 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -3,14 +3,14 @@ title: Upgrade guide description: Guide to update between major Powertools for AWS Lambda (TypeScript) versions --- -## Migrate from v1 to v2 +!!! note "We expect to release v2 by the end of February 2024." +## Migrate from v1 to v2 V2 is focused on official support for ESM (ECMAScript modules). We've made other minimal breaking changes to make your transition to v2 as smooth as possible. ### Quick summary - | Area | Change | Code change required | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------- | | **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | From 809d21c71ce75242af903c21d53fd057e070d8fc Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 16:53:26 +0100 Subject: [PATCH 19/22] added banners --- docs/overrides/main.html | 5 +++++ docs/upgrade.md | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/overrides/main.html b/docs/overrides/main.html index 0d556b6813..f36a4c7961 100644 --- a/docs/overrides/main.html +++ b/docs/overrides/main.html @@ -5,4 +5,9 @@ Click here to go to latest. +{% endblock %} + +{% block announce %} +Version 2 is coming soon 🔥 Check out the upgrade guide to see what's +new. {% endblock %} \ No newline at end of file diff --git a/docs/upgrade.md b/docs/upgrade.md index ce60bcf26f..e173e630e9 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -166,9 +166,9 @@ Logger `sampleRateValue` **continues** to determine the percentage of concurrent !!! note "Disregard if you are not customizing log output with a [custom log formatter](./core/logger.md#custom-log-formatter-bring-your-own-formatter)." -In v1, `Logger` combined both [standard]((./core/logger.md#standard-structured-keys)) and [custom keys](./core/logger.md#appending-persistent-additional-log-keys-and-values) as a single argument, _e.g., `formatAttributes(attributes: UnformattedAttributes)`_. It expected a plain object with keys and values you wanted in the final log output. +In v1, `Logger` exposed the [standard](./core/logger.md#standard-structured-keys) as a single argument, _e.g., `formatAttributes(attributes: UnformattedAttributes)`_. It expected a plain object with keys and values you wanted in the final log output. -In v2, you have more control over **standard** (`attributes`) and **custom keys** (`additionalLogAttributes`) in the `formatAttributes` method. Also, you now return a `LogItem` object to increase type safety when defining the final log output. +In v2, you have more control over **standard** (`attributes`) and [**custom keys**](./core/logger.md#appending-persistent-additional-log-keys-and-values) (`additionalLogAttributes`) in the `formatAttributes` method. Also, you now return a `LogItem` object to increase type safety when defining the final log output. === "Before" From feb94e611fd5c1cfa12c15ae53b6496eb3b80b25 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Fri, 9 Feb 2024 17:04:48 +0100 Subject: [PATCH 20/22] added use esm section --- docs/upgrade.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index e173e630e9..6f0cdcb3a0 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -47,9 +47,16 @@ export const handler = async (_event: unknown, _context: unknown) => { In v2, we improved tree-shaking support to help you reduce your function bundle size. We would love to hear your feedback on further improvements we could make. -While we recommend using ES Modules, we understand that this change might not be possible for everyone. If you're unable to use ES Modules, you can continue to use the `require` syntax to import the package. Powertools for AWS Lambda (TypeScript) will continue to support this syntax by shipping CommonJS modules alongside ES Modules. +### Unable to use ESM? -In some cases, even when opting for ES Modules, you might still need to use the `require` syntax to import a package. For example, if you're using a package that doesn't support ES Modules, or if one of your transitive dependencies is using the `require` syntax like it's the case for `@aws-lambda-powertools/tracer` which relies on the AWS X-Ray SDK for Node.js. In these cases, you can still use ES Modules for the rest of your codebase and set a special build flag to tell your bundler to inject a banner at the top of the file to use the `require` syntax for the specific package. +!!! note "We recommend using ESM for the best experience _(top-level await, smaller bundle size etc.)_." + +If you're unable to use ESM, you can still use the `require` syntax to import the package. We will continue to support it by shipping CommonJS modules alongside ESM. + +You might still need the `require` syntax when using a dependency or a transitive dependency that doesn't support ESM. For example, Tracer _(`@aws-lambda-powertools/tracer`)_ relies on the AWS X-Ray SDK for Node.js which uses `require`. + +When that happens, you can instruct your bundler to use the `require` syntax for specific dependencies while using ESM for everything else. This is commonly known as [polyfill](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill){target="_blank"}. +Here is an example using `esbuild` bundler. === "With AWS CDK" From 4535263d3301e85219fe5d4a7d29792ecf7c00c5 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Tue, 13 Feb 2024 16:40:49 +0100 Subject: [PATCH 21/22] Apply suggestions from code review Co-authored-by: Heitor Lessa --- docs/upgrade.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 6f0cdcb3a0..0bc9b2e74c 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -14,7 +14,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | Area | Change | Code change required | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------- | | **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | -| **Middy.js ** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | +| **Middy.js** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | | **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | @@ -137,11 +137,13 @@ In v2, you can now import only the Middy.js middlewares you want to use from a s === "After" - ```typescript hl_lines="2 4 6" + ```typescript hl_lines="2 5 8" import { Logger } from '@aws-lambda-powertools/logger'; import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware'; + import { Tracer } from '@aws-lambda-powertools/tracer'; import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware'; + import { Metrics } from '@aws-lambda-powertools/metrics'; import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'; ``` From 870b40e2d9f335affccccc11b58af268536680f6 Mon Sep 17 00:00:00 2001 From: Andrea Amorosi Date: Tue, 13 Feb 2024 16:43:23 +0100 Subject: [PATCH 22/22] chore: add types before & after --- docs/upgrade.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/upgrade.md b/docs/upgrade.md index 0bc9b2e74c..72d196722b 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -14,7 +14,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | Area | Change | Code change required | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------- | | **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | -| **Middy.js** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | +| **Middy.js** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | | **Logger** | Changed [log sampling](./core/logger.md#sampling-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | | **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | @@ -154,6 +154,18 @@ In v1, you could import package types from each package under `/lib`, for exampl In v2, you can now directly import from the `types` subpath export, e.g., `@aws-lambda-powertools/logger/types`. This will optimize your bundle size, standardize types import across packages, future-proofing growth. +=== "Before" + + ```typescript + import { LogAttributes, UnformattedAttributes } from '@aws-lambda-powertools/logger/lib/types'; + ``` + +=== "After" + + ```typescript + import { LogAttributes, UnformattedAttributes } from '@aws-lambda-powertools/logger/types'; + ``` + ## Logger ### Log sampling