diff --git a/docs/core/logger.md b/docs/core/logger.md index 33e3b8a391..6e66a92787 100644 --- a/docs/core/logger.md +++ b/docs/core/logger.md @@ -111,7 +111,7 @@ This functionality will include the following keys in your structured logs: === "Middy Middleware" !!! tip "A note about Middy" - We guarantee support for both Middy.js `v4.x` & `v5.x` with the latter being available only if you are using ES modules. + We guarantee support for Middy.js `v4.x` through `v6.x` versions. Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. ```typescript hl_lines="2 14" diff --git a/docs/core/metrics.md b/docs/core/metrics.md index 8d11281f19..42bc929ebe 100644 --- a/docs/core/metrics.md +++ b/docs/core/metrics.md @@ -70,6 +70,7 @@ These settings will be used across all metrics emitted: | -------------------- | ---------------------------------------------------------------- | ------------------------------ | ------------------- | -------------- | ------------------- | --------------------- | | **Service** | Optionally, sets **service** metric dimension across all metrics | `POWERTOOLS_SERVICE_NAME` | `service_undefined` | Any string | `serverlessAirline` | `serviceName` | | **Metric namespace** | Logical container where all metrics will be placed | `POWERTOOLS_METRICS_NAMESPACE` | `default_namespace` | Any string | `serverlessAirline` | `default_namespace` | +| **Enabled** | Whether to emit metrics to standard output or not | `POWERTOOLS_METRICS_ENABLED` | `true` | Boolean | `false` | | !!! tip Use your application name or main service as the metric namespace to easily group all metrics @@ -199,7 +200,7 @@ You can add default dimensions to your metrics by passing them as parameters in === "Middy middleware" !!! tip "A note about Middy" - We guarantee support for both Middy.js `v4.x` & `v5.x` with the latter being available only if you are using ES modules. + We guarantee support for Middy.js `v4.x` through `v6.x` versions. Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. ```typescript hl_lines="24-26" @@ -465,22 +466,26 @@ Keep the following formula in mind: `unique metric = (metric_name + dimension_na 1. Metadata should be added before calling `addMetric()` to ensure it's included in the same EMF blob. 2. Single metrics are emitted as soon as `addMetric()` is called, so you don't need to call `publishStoredMetrics()`. +### Customizing the logger + +You can customize how Metrics logs warnings and debug messages to standard output by passing a custom logger as a constructor parameter. This is useful when you want to silence warnings or debug messages, or when you want to log them to a different output. + +=== "Custom logger" + + ```typescript hl_lines="4 9" + --8<-- "examples/snippets/metrics/customLogger.ts" + ``` + ## Testing your code -When unit testing your code that uses the `Metrics` utility, you may want to silence the logs emitted by the utility or assert that metrics are being emitted correctly. By default, the utility manages its own `console` instance, which means that you can't easily access or mock the logs emitted by the utility. +When unit testing your code that uses the Metrics utility, you may want to silence the logs emitted by the utility. To do so, you can set the `POWERTOOLS_DEV` environment variable to `true`. This instructs the utility to not emit any logs to standard output. -To make it easier to test your code, you can set the `POWERTOOLS_DEV` environment variable to `true` to instruct the utility to use the global `console` object instead of its own. +If instead you want to spy on the logs emitted by the utility, you must set the `POWERTOOLS_DEV` environment variable to `true` in conjunction with the `POWERTOOLS_METRICS_ENABLED` environment variable also set to `true`. -This allows you to spy on the logs emitted by the utility and assert that the metrics are being emitted correctly. +When `POWERTOOLS_DEV` is enabled, Metrics uses the global `console` to emit metrics to standard out. This allows you to easily spy on the logs emitted and make assertions on them. === "Spying on emitted metrics" - ```typescript hl_lines="4 10" + ```typescript hl_lines="4-5 12" --8<-- "examples/snippets/metrics/testingMetrics.ts" ``` - -When running your tests with both [Jest](https://jestjs.io) and [Vitest](http://vitest.dev), you can use the `--silent` flag to silence the logs emitted by the utility. - -```bash title="Disabling logs while testing" -export POWERTOOLS_DEV=true && npx vitest --silent -``` diff --git a/docs/core/tracer.md b/docs/core/tracer.md index 8c3977deda..8ea03d6768 100644 --- a/docs/core/tracer.md +++ b/docs/core/tracer.md @@ -154,7 +154,7 @@ You can quickly start by importing the `Tracer` class, initialize it outside the === "Middy Middleware" !!! tip "A note about Middy" - We guarantee support for both Middy.js `v4.x` & `v5.x` with the latter being available only if you are using ES modules. + We guarantee support for Middy.js `v4.x` through `v6.x` versions. Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. ```typescript hl_lines="2 15 17" diff --git a/docs/index.md b/docs/index.md index 70b62082b4..8e8d074a86 100644 --- a/docs/index.md +++ b/docs/index.md @@ -56,12 +56,12 @@ You can use Powertools for AWS Lambda (TypeScript) by installing it with your fa | Feature | Install | Default dependency | | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------- | - | **[Tracer](./core/tracer.md#install)** | **`npm i @aws-lambda-powertools/tracer`**{.copyMe}:clipboard: | `aws-xray-sdk-core` | - | **[Idempotency](./utilities/idempotency.md#install)** | **`npm i @aws-lambda-powertools/idempotency @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb`**{.copyMe}:clipboard: | `jmespath` | - | **[Parameters (SSM)](./utilities/parameters.md#install)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-ssm`**{.copyMe}:clipboard: | | - | **[Parameters (Secrets Manager)](./utilities/parameters.md#install)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager`**{.copyMe}:clipboard: | | - | **[Parameters (AppConfig)](./utilities/parameters.md#install)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata`**{.copyMe}:clipboard: | | - | **[Parser](./utilities/parser.md#install)** | **`npm i @aws-lambda-powertools/parser zod@~3`**{.copyMe}:clipboard: | | + | **[Tracer](./core/tracer.md)** | **`npm i @aws-lambda-powertools/tracer`**{.copyMe}:clipboard: | `aws-xray-sdk-core` | + | **[Idempotency](./utilities/idempotency.md)** | **`npm i @aws-lambda-powertools/idempotency @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb`**{.copyMe}:clipboard: | | + | **[Parameters (SSM)](./utilities/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-ssm`**{.copyMe}:clipboard: | | + | **[Parameters (Secrets Manager)](./utilities/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager`**{.copyMe}:clipboard: | | + | **[Parameters (AppConfig)](./utilities/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata`**{.copyMe}:clipboard: | | + | **[Parser](./utilities/parser.md)** | **`npm i @aws-lambda-powertools/parser zod@~3`**{.copyMe}:clipboard: | | === "Lambda Layer" @@ -223,27 +223,18 @@ You can use Powertools for AWS Lambda (TypeScript) by installing it with your fa === "Amplify" - ```zsh hl_lines="9 19" - # Create a new one with the layer - ❯ amplify add function - ? Select which capability you want to add: Lambda function (serverless function) - ? Provide an AWS Lambda function name: - ? Choose the runtime that you want to use: NodeJS - ? Do you want to configure advanced settings? Yes - ... - ? Do you want to enable Lambda layers for this function? Yes - ? Enter up to 5 existing Lambda layer ARNs (comma-separated): arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:16 - ❯ amplify push -y - - # Updating an existing function and add the layer - ❯ amplify update function - ? Select the Lambda function you want to update test2 - General information - - Name: - ? Which setting do you want to update? Lambda layers configuration - ? Do you want to enable Lambda layers for this function? Yes - ? Enter up to 5 existing Lambda layer ARNs (comma-separated): arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:16 - ? Do you want to edit the local lambda function now? No + Remember to replace the region with your AWS region, e.g., `eu-west-1`. Amplify Gen 2 currently does not support obtaining the region dynamically. + + ```typescript hl_lines="9 19" + import { defineFunction } from "@aws-amplify/backend"; + + export const myFunction = defineFunction({ + name: "my-function", + layers: { + "@aws-lambda-powertools/*": + "arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:16", + }, + }); ``` ### Lambda Layer @@ -334,6 +325,7 @@ Core utilities such as Tracing, Logging, and Metrics will be available across al | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------- | | **POWERTOOLS_SERVICE_NAME** | Set service name used for tracing namespace, metrics dimension and structured logging | All | `service_undefined` | | **POWERTOOLS_METRICS_NAMESPACE** | Set namespace used for metrics | [Metrics](core/metrics.md) | `default_namespace` | +| **POWERTOOLS_METRICS_ENABLED** | Explicitly disables emitting metrics to stdout | [Metrics](core/metrics.md) | `true` | | **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](core/tracer.md) | `true` | | **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Capture Lambda or method return as metadata. | [Tracer](core/tracer.md) | `true` | | **POWERTOOLS_TRACER_CAPTURE_ERROR** | Capture Lambda or method exception as metadata. | [Tracer](core/tracer.md) | `true` | @@ -348,6 +340,18 @@ Core utilities such as Tracing, Logging, and Metrics will be available across al Each Utility page provides information on example values and allowed values. +### Optimizing for non-production environments + +Whether you're prototyping locally or against a non-production environment, you can use `POWERTOOLS_DEV` to increase verbosity across multiple utilities. + +When `POWERTOOLS_DEV` is set to a truthy value (`1`, `true`), it'll have the following effects: + +| Utility | Effect | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| __Logger__ | Increase JSON indentation to 4 and uses global `console` to emit logs to ease testing and local debugging when running functions locally. However, Amazon CloudWatch Logs view will degrade as each new line is treated as a new message | +| __Tracer__ | Disables tracing operations in non-Lambda environments. This already happens automatically in the Tracer utility | +| __Metrics__ | Disables emitting metrics to stdout. Can be overridden by setting `POWERTOOLS_METRICS_ENABLED` to `true` | + ## Support Powertools for AWS Lambda (TypeScript) There are many ways you can help us gain future investments to improve everyone's experience: diff --git a/docs/overrides/main.html b/docs/overrides/main.html index 62c9e3ce28..0d556b6813 100644 --- a/docs/overrides/main.html +++ b/docs/overrides/main.html @@ -5,11 +5,4 @@ Click here to go to latest. -{% endblock %} - -{% block announce %} -On September 1st, 2024 v1 of Powertools for AWS Lambda (TypeScript) has reached - End-of-Life. We recommend you to upgrade to v2. {% endblock %} \ No newline at end of file diff --git a/docs/upgrade.md b/docs/upgrade.md index d8e83b514f..91a0115bb1 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -198,7 +198,7 @@ Below is an example of how to configure your `.eslintrc.json` file: ### Log sampling -!!! note "Disregard if you are not using the [log sampling feature](./core/logger.md#sampling-logs)." +!!! note "Disregard if you are not using the [log sampling feature](./core/logger.md#sampling-debug-logs)." In v1, log sampling implementation was inconsistent from other Powertools for AWS Lambda languages _(Python, .NET, and Java)_. @@ -217,7 +217,7 @@ Logger `sampleRateValue` **continues** to determine the percentage of concurrent 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**](./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. +In v2, you have more control over **standard** (`attributes`) and [**custom keys**](./core/logger.md#appending-additional-keys) (`additionalLogAttributes`) in the `formatAttributes` method. Also, you now return a `LogItem` object to increase type safety when defining the final log output. === "Before" diff --git a/docs/utilities/idempotency.md b/docs/utilities/idempotency.md index 15ae8c5779..878f06042c 100644 --- a/docs/utilities/idempotency.md +++ b/docs/utilities/idempotency.md @@ -187,7 +187,7 @@ The configuration options for the `@idempotent` decorator are the same as the on ### MakeHandlerIdempotent Middy middleware !!! tip "A note about Middy" - We guarantee support for both Middy.js `v4.x` & `v5.x` with the latter being available only if you are using ES modules. + We guarantee support for Middy.js `v4.x` through `v6.x` versions. Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. If you are using [Middy.js](https://middy.js.org){target="_blank"} as your middleware engine, you can use the `makeHandlerIdempotent` middleware to make your Lambda handler idempotent. diff --git a/docs/utilities/parser.md b/docs/utilities/parser.md index 348b1c23bf..d1c534f9fe 100644 --- a/docs/utilities/parser.md +++ b/docs/utilities/parser.md @@ -1,7 +1,6 @@ --- title: Parser (Zod) descrition: Utility -status: new --- @@ -18,8 +17,6 @@ This utility provides data validation and parsing using [Zod](https://zod.dev){t ## Getting started -### Install - ```bash npm install @aws-lambda-powertools/parser zod@~3 ``` diff --git a/examples/snippets/metrics/customLogger.ts b/examples/snippets/metrics/customLogger.ts new file mode 100644 index 0000000000..16acf4f9ab --- /dev/null +++ b/examples/snippets/metrics/customLogger.ts @@ -0,0 +1,12 @@ +import { LogLevel, Logger } from '@aws-lambda-powertools/logger'; +import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics'; + +const logger = new Logger({ logLevel: LogLevel.CRITICAL }); +const metrics = new Metrics({ + serviceName: 'serverless-airline', + namespace: 'orders', + singleMetric: true, + logger, +}); + +metrics.addMetric('successfulBooking', MetricUnit.Count, 1); diff --git a/examples/snippets/metrics/testingMetrics.ts b/examples/snippets/metrics/testingMetrics.ts index ec8966ea55..af2d4b796c 100644 --- a/examples/snippets/metrics/testingMetrics.ts +++ b/examples/snippets/metrics/testingMetrics.ts @@ -2,17 +2,20 @@ import { describe, expect, it, vi } from 'vitest'; vi.hoisted(() => { process.env.POWERTOOLS_DEV = 'true'; + process.env.POWERTOOLS_METRICS_ENABLED = 'true'; }); describe('Metrics tests', () => { it('emits metrics properly', async () => { // Prepare - const metricsSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + const metricsEmittedSpy = vi + .spyOn(console, 'log') + .mockImplementation(() => {}); // Act // ... // Assess - expect(metricsSpy).toHaveBeenCalledOnce(); + expect(metricsEmittedSpy).toHaveBeenCalledOnce(); }); }); diff --git a/mkdocs.yml b/mkdocs.yml index 2e28890c77..2451b070ed 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -11,7 +11,7 @@ nav: - API reference: api/" target="_blank - Upgrade guide: upgrade.md - We Made This (Community): we_made_this.md - - Workshop 🆕: https://s12d.com/powertools-for-aws-lambda-workshop" target="_blank + - Workshop: https://s12d.com/powertools-for-aws-lambda-workshop" target="_blank - Roadmap: roadmap.md - Features: - core/tracer.md