Skip to content

Commit

Permalink
docs: multiple minor improvements (#3387)
Browse files Browse the repository at this point in the history
  • Loading branch information
dreamorosi authored Nov 29, 2024
1 parent 93a19a5 commit 95ebfbb
Show file tree
Hide file tree
Showing 11 changed files with 70 additions and 56 deletions.
2 changes: 1 addition & 1 deletion docs/core/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
27 changes: 16 additions & 11 deletions docs/core/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
```
2 changes: 1 addition & 1 deletion docs/core/tracer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
58 changes: 31 additions & 27 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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: <NAME-OF-FUNCTION>
? 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: <NAME-OF-FUNCTION>
? 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
Expand Down Expand Up @@ -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` |
Expand All @@ -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:
Expand Down
7 changes: 0 additions & 7 deletions docs/overrides/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,4 @@
<a href="{{ '../' ~ base_url }}">
<strong>Click here to go to latest.</strong>
</a>
{% endblock %}

{% block announce %}
On September 1st, 2024 v1 of Powertools for AWS Lambda (TypeScript) <a
href="https://github.com/aws-powertools/powertools-lambda-typescript/issues/2224" target="_blank">has reached
End-of-Life</a>. We recommend you to <a href="https://docs.powertools.aws.dev/lambda/typescript/latest/upgrade/"
target="_blank">upgrade to v2</a>.
{% endblock %}
4 changes: 2 additions & 2 deletions docs/upgrade.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)_.

Expand All @@ -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"

Expand Down
2 changes: 1 addition & 1 deletion docs/utilities/idempotency.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 0 additions & 3 deletions docs/utilities/parser.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
title: Parser (Zod)
descrition: Utility
status: new
---

<!-- markdownlint-disable MD043 --->
Expand All @@ -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
```
Expand Down
12 changes: 12 additions & 0 deletions examples/snippets/metrics/customLogger.ts
Original file line number Diff line number Diff line change
@@ -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);
7 changes: 5 additions & 2 deletions examples/snippets/metrics/testingMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 95ebfbb

Please sign in to comment.