diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.md b/.github/ISSUE_TEMPLATE/BUG_REPORT.md deleted file mode 100644 index 9b40228442..0000000000 --- a/.github/ISSUE_TEMPLATE/BUG_REPORT.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: "Bug (module name): short issue description" -labels: bug, triage ---- - - - - - - -## Bug description - - - - - -### Expected Behavior - - - -### Current Behavior - - - -### Possible Solution - - - -### Steps to Reproduce - - - -1. -2. -3. -4. - -### Environment - -* **Powertools version used**: -* **Packaging format (Layers, npm)**: -* **AWS Lambda function runtime:** -* **Debugging logs:** - -### Related issues, RFCs - - - - diff --git a/.github/ISSUE_TEMPLATE/DOC_IMPROVEMENT.md b/.github/ISSUE_TEMPLATE/DOC_IMPROVEMENT.md deleted file mode 100644 index 89144bac46..0000000000 --- a/.github/ISSUE_TEMPLATE/DOC_IMPROVEMENT.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -name: Documentation improvement -about: Suggest a documentation update, improvement -title: "Documentation (module name): short issue description" -labels: documentation ---- - - - - -## Description of the improvement - -**Summary of the proposal** - - -**How, where did you look for information** - - -**Missing or unclear documentation** - - -**Improvement** - - - -### Related existing documentation - - - - - - - -### Related issues, RFCs - - - - \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md deleted file mode 100644 index 99af78e849..0000000000 --- a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: "Feature (module name): short issue description" -labels: feature-request, triage ---- - - - - -## Description of the feature request - -**Problem statement** - - -**Summary of the feature** - - - - -**Code examples** - - -**Benefits for you and the wider AWS community** - - -**Describe alternatives you've considered** - - -**Additional context** - - -### Related issues, RFCs - - - - diff --git a/.github/ISSUE_TEMPLATE/RFC.md b/.github/ISSUE_TEMPLATE/RFC.md deleted file mode 100644 index d5ee8d6d3a..0000000000 --- a/.github/ISSUE_TEMPLATE/RFC.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -name: RFC -about: Feature design and proposals -title: 'RFC (module name): short issue description' -labels: RFC, triage -assignees: '' -approved by: '' ---- - -## Key information - -* RFC PR: (leave this empty) -* Related issue(s), if known: -* Area: (i.e. Tracer, Metrics, Logger, etc.) -* Meet [tenets](https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#tenets): (Yes/no) -* Approved by: '' -* Reviewed by: '' - -## Summary -[summary]: #summary - - - -## Motivation -[motivation]: #motivation - - - -## Proposal -[proposal]: #proposal - - - - - - - - -## User Experience - - - - - - - - - - -## Drawbacks -[drawbacks]: #drawbacks - - - - - - - -## Rationale and alternatives -[rationale-and-alternatives]: #rationale-and-alternatives - - - - - - - -## Unresolved questions -[unresolved-questions]: #unresolved-questions - - \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000..173e45e7df --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,89 @@ +name: Bug report +description: Report a reproducible bug to help us improve +title: "Bug: TITLE" +labels: ["bug", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a bug report. Before you start, make sure that [the bug hasn't been reported already](https://github.com/awslabs/aws-lambda-powertools-typescript/issues). + + Please add as much information as possible to help us reproduce, and remove any potential sensitive data. + - type: textarea + id: expected_behaviour + attributes: + label: Expected Behaviour + description: Please share details on the behaviour you expected + validations: + required: true + - type: textarea + id: current_behaviour + attributes: + label: Current Behaviour + description: Please share details on the current issue + validations: + required: true + - type: textarea + id: code_snippet + attributes: + label: Code snippet + description: Please share a code snippet to help us reproduce the issue + render: JavaScript + validations: + required: true + - type: textarea + id: solution + attributes: + label: Possible Solution + description: If known, please suggest a potential resolution + validations: + required: false + - type: textarea + id: steps + attributes: + label: Steps to Reproduce + description: Please share how we might be able to reproduce this issue + validations: + required: true + - type: input + id: version + attributes: + label: AWS Lambda Powertools for TypeScript version + placeholder: "latest, 1.3.0" + value: latest + validations: + required: true + - type: dropdown + id: runtime + attributes: + label: AWS Lambda function runtime + options: + - 12.x + - 14.x + - 16.x + validations: + required: true + - type: dropdown + id: packaging + attributes: + label: Packaging format used + options: + - Lambda Layers + - Npm + multiple: true + validations: + required: true + - type: textarea + id: logs + attributes: + label: Debugging logs + description: If available, please share [debugging logs](https://awslabs.github.io/aws-lambda-powertools-python/#debug-mode) + render: Shell + validations: + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: After creating an issue, please wait until it is triaged and confirmed by a maintainer before implementing it. This will reduce amount of rework and the chance that a pull request gets rejected. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index ec4bb386bc..1aac771b9b 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1 +1,5 @@ -blank_issues_enabled: false \ No newline at end of file +blank_issues_enabled: false +contact_links: + - name: Ask a question + url: https://github.com/awslabs/aws-lambda-powertools-typescript/discussions/new + about: Ask a general question about Lambda Powertools \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/documentation_improvements.yml b/.github/ISSUE_TEMPLATE/documentation_improvements.yml new file mode 100644 index 0000000000..d52df5b994 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation_improvements.yml @@ -0,0 +1,51 @@ +name: Documentation improvements +description: Suggest a documentation update to improve everyone's experience +title: "Docs: TITLE" +labels: ["documentation", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for helping us improve everyone's experience. We review documentation updates on a case by case basis. + - type: textarea + id: search_area + attributes: + label: What were you searching in the docs? + description: Please help us understand how you looked for information that was either unclear or not available + validations: + required: true + - type: input + id: area + attributes: + label: Is this related to an existing documentation section? + description: Please share a link, if applicable + validations: + required: false + - type: textarea + id: idea + attributes: + label: How can we improve? + description: Please share your thoughts on how we can improve this experience + render: Markdown + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: Got a suggestion in mind? + description: Please suggest a proposed update + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: I understand the final update might be different from my proposed suggestion, or refused. + required: true + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: After creating an issue, please wait until it is triaged and confirmed by a maintainer before implementing it. This will reduce amount of rework and the chance that a pull request gets rejected. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000..5abeb0a7f4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,48 @@ +name: Feature request +description: Suggest an idea for Lambda Powertools +title: "Feature request: TITLE" +labels: ["feature-request", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for taking the time to suggest an idea to the Lambda Powertools project. + + *Future readers*: Please react with 👍 and your use case to help us understand customer demand. + - type: textarea + id: problem + attributes: + label: Use case + description: Please help us understand your use case or problem you're facing + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: Solution/User Experience + description: Please share what a good solution would look like to this use case + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternative solutions + description: Please describe what alternative solutions to this use case, if any + render: Markdown + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This feature request meets [Lambda Powertools Tenets](https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#tenets) + required: true + - label: Should this be considered in other Lambda Powertools languages? i.e. [Python](https://github.com/awslabs/aws-lambda-powertools-python/), [Java](https://github.com/awslabs/aws-lambda-powertools-java/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: After creating an issue, please wait until it is triaged and confirmed by a maintainer before implementing it. This will reduce amount of rework and the chance that a pull request gets rejected. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/maintenance.yml b/.github/ISSUE_TEMPLATE/maintenance.yml new file mode 100644 index 0000000000..ec405be86d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/maintenance.yml @@ -0,0 +1,63 @@ +name: Maintenance +description: Suggest an activity to help address tech debt, governance, and anything internal +title: "Maintenance: TITLE" +labels: ["internal", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for taking the time to help us improve this project. + + *Future readers*: Please react with 👍 and your use case to help us understand customer demand. + - type: textarea + id: activity + attributes: + label: Summary + description: Please provide an overview in one or two paragraphs + validations: + required: true + - type: textarea + id: importance + attributes: + label: Why is this needed? + description: Please help us understand the value so we can prioritize it accordingly + validations: + required: true + - type: dropdown + id: area + attributes: + label: Which area does this relate to? + multiple: true + options: + - Automation + - Governance + - Tests + - Types + - Tracer + - Logger + - Metrics + - Parameters + - Idempotency + - Other + - type: textarea + id: suggestion + attributes: + label: Solution + description: If available, please share what a good solution would look like + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This request meets [Lambda Powertools Tenets](https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#tenets) + required: true + - label: Should this be considered in other Lambda Powertools languages? i.e. [TypeScript](https://github.com/awslabs/aws-lambda-powertools-typescript/), [Java](https://github.com/awslabs/aws-lambda-powertools-java/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: After creating an issue, please wait until it is triaged and confirmed by a maintainer before implementing it. This will reduce amount of rework and the chance that a pull request gets rejected. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/rfc.yml b/.github/ISSUE_TEMPLATE/rfc.yml new file mode 100644 index 0000000000..b5b1b5c20f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/rfc.yml @@ -0,0 +1,99 @@ +name: Request for Comments (RFC) +description: Feature design and detailed proposals +title: "RFC: TITLE" +labels: ["RFC", "triage"] +body: + - type: markdown + attributes: + value: | + Thank you for submitting a RFC. Please add as many details as possible to help further enrich this design. + - type: input + id: relation + attributes: + label: Is this related to an existing feature request or issue? + description: Please share a link, if applicable + - type: dropdown + id: area + attributes: + label: Which AWS Lambda Powertools utility does this relate to? + options: + - Tracer + - Logger + - Metrics + - Parameters + - Idempotency + - Other + validations: + required: true + - type: textarea + id: summary + attributes: + label: Summary + description: Please provide an overview in one or two paragraphs + validations: + required: true + - type: textarea + id: problem + attributes: + label: Use case + description: Please share the use case and motivation behind this proposal + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposal + description: Please explain the design in detail, so anyone familiar with the project could implement it + placeholder: What the user experience looks like before and after this design? + validations: + required: true + - type: textarea + id: scope + attributes: + label: Out of scope + description: Please explain what should be considered out of scope in your proposal + validations: + required: true + - type: textarea + id: challenges + attributes: + label: Potential challenges + description: Nothing is perfect. Please share what common challenges, edge cases, unresolved areas, and suggestions on how to mitigate them + validations: + required: true + - type: textarea + id: integrations + attributes: + label: Dependencies and Integrations + description: If applicable, please share whether this feature has additional dependencies, and how it might integrate with other utilities available + validations: + required: false + - type: textarea + id: alternatives + attributes: + label: Alternative solutions + description: Please describe what alternative solutions to this use case, if any + render: Markdown + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: This feature request meets [Lambda Powertools Tenets](https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#tenets) + required: true + - label: Should this be considered in other Lambda Powertools languages? i.e. [Python](https://github.com/awslabs/aws-lambda-powertools-python/), [Java](https://github.com/awslabs/aws-lambda-powertools-java/) + required: false + - type: markdown + attributes: + value: | + --- + + **Disclaimer**: After creating an issue, please wait until it is triaged and confirmed by a maintainer before implementing it. This will reduce amount of rework and the chance that a pull request gets rejected. + + Metadata information for admin purposes, please leave them empty. + + * RFC PR: + * Approved by: '' + * Reviewed by: '' \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/share_your_work.yml b/.github/ISSUE_TEMPLATE/share_your_work.yml new file mode 100644 index 0000000000..2ee619fccd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/share_your_work.yml @@ -0,0 +1,56 @@ +name: I Made This (showcase your work) +description: Share what you did with Powertools 💞💞. Blog post, workshops, presentation, sample apps, etc. +title: "[I Made This]: " +labels: ["community-content"] +body: + - type: markdown + attributes: + value: Thank you for helping spread the word out on Powertools, truly! + - type: input + id: content + attributes: + label: Link to your material + description: | + Please share the original link to your material. + + *Note: Short links will be expanded when added to Powertools documentation* + validations: + required: true + - type: textarea + id: description + attributes: + label: Description + description: Describe in one paragraph what's in it for them (readers) + validations: + required: true + - type: input + id: author + attributes: + label: Preferred contact + description: What's your preferred contact? We'll list it next to this content + validations: + required: true + - type: input + id: author-social + attributes: + label: (Optional) Social Network + description: If different from preferred contact, what's your preferred contact for social interactions? + validations: + required: false + - type: textarea + id: notes + attributes: + label: (Optional) Additional notes + description: | + Any notes you might want to share with us related to this material. + + *Note: These notes are explicitly to Powertools maintainers. It will not be added to the community resources page.* + validations: + required: false + - type: checkboxes + id: acknowledgment + attributes: + label: Acknowledgment + options: + - label: I understand this content may be removed from Powertools documentation if it doesn't conform with the [Code of Conduct](https://aws.github.io/code-of-conduct) + required: true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/support_powertools.yml b/.github/ISSUE_TEMPLATE/support_powertools.yml new file mode 100644 index 0000000000..a667a13f5e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/support_powertools.yml @@ -0,0 +1,64 @@ +name: Support Lambda Powertools (become a reference) +description: Add your organization's name or logo to the Lambda Powertools documentation +title: "[Support Lambda Powertools]: <your organization name>" +labels: ["customer-reference"] +body: + - type: markdown + attributes: + value: | + Thank you for becoming a reference customer. Your support means a lot to us. It also helps new customers to know who're using Lambda Powertools. + + If you would like us to also display your organization's logo, please share a link in the `Company logo` field. + - type: input + id: organization + attributes: + label: Organization Name + description: Please share the name of your organization + placeholder: ACME + validations: + required: true + - type: input + id: name + attributes: + label: Your Name + description: Please share your name + validations: + required: true + - type: input + id: job + attributes: + label: Your current position + description: Please share your current position at your company + validations: + required: true + - type: input + id: logo + attributes: + label: (Optional) Company logo + description: Company logo you want us to display. You also allow us to resize for optimal placement in the documentation. + validations: + required: false + - type: textarea + id: use_case + attributes: + label: (Optional) Use case + description: How are you using Lambda Powertools today? *features, etc.* + validations: + required: false + - type: checkboxes + id: other_languages + attributes: + label: Also using other Lambda Powertools languages? + options: + - label: Python + required: false + - label: Java + required: false + - label: .NET + required: false + - type: markdown + attributes: + value: | + *By raising a Support Lambda Powertools issue, you are granting AWS permission to use your company's name (and/or logo) for the limited purpose described here. You are also confirming that you have authority to grant such permission.* + + *You can opt-out at any time by commenting or reopening this issue.* \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index eaf2fd4a19..f551ab2f2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,22 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + + +### Bug Fixes + +* **metrics:** metadata and dimensions not cleared on publish ([#1129](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1129)) ([b209c30](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/b209c30df92da07875f204f7f211294feea729db)) + + +### Features + +* **all:** moved EnvService to commons + exposed getXrayTraceId in tracer ([#1123](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1123)) ([c8e3c15](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/c8e3c15b64142ebe6f43835a5917ecba26293a32)) + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/docs/core/logger.md b/docs/core/logger.md index b304ba69a8..ab0bd44986 100644 --- a/docs/core/logger.md +++ b/docs/core/logger.md @@ -52,12 +52,12 @@ The library requires two settings. You can set them as environment variables, or These settings will be used across all logs emitted: -| Setting | Description | Environment variable | Constructor parameter | -|-------------------|------------------------------------------------------------------------------------------------------------------|---------------------------|-----------------------| -| **Logging level** | Sets how verbose Logger should be (INFO, by default). Supported values are: `DEBUG`, `INFO`, `WARN`, `ERROR` | `LOG_LEVEL` | `logLevel` | -| **Service name** | Sets the name of service of which the Lambda function is part of, that will be present across all log statements | `POWERTOOLS_SERVICE_NAME` | `serviceName` | - -For a **complete list** of supported environment variables, refer to [this section](./../index.md#environment-variables). +| Setting | Description | Environment variable | Constructor parameter | +|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------|-----------------------| +| **Service name** | Sets the name of service of which the Lambda function is part of, that will be present across all log statements | `POWERTOOLS_SERVICE_NAME` | `serviceName` | +| **Logging level** | Sets how verbose Logger should be (INFO, by default). Supported values are: `DEBUG`, `INFO`, `WARN`, `ERROR` | `LOG_LEVEL` | `logLevel` | +| **Log incoming event** | Whether to log or not the incoming event when using the decorator or middleware. Supported values are: `true`, or `false`, disabled by default | `POWERTOOLS_LOGGER_LOG_EVENT` | `logEvent` | +| **Debug log sampling** | Probability that a Lambda invocation will print all the log items regardless of the log level setting. Supported values range from `0.0` to `1` | `POWERTOOLS_LOGGER_SAMPLE_RATE` | `sampleRateValue` | #### Example using AWS Serverless Application Model (SAM) @@ -201,7 +201,7 @@ In each case, the printed log will look like this: When debugging in non-production environments, you can instruct Logger to log the incoming event with the middleware/decorator parameter `logEvent` or via `POWERTOOLS_LOGGER_LOG_EVENT` env var set to `true`. ???+ warning -This is disabled by default to prevent sensitive info being logged + This is disabled by default to prevent sensitive info being logged === "Middy Middleware" diff --git a/docs/core/metrics.md b/docs/core/metrics.md index e2770de640..3b2d4baa3f 100644 --- a/docs/core/metrics.md +++ b/docs/core/metrics.md @@ -68,10 +68,8 @@ These settings will be used across all metrics emitted: | Setting | Description | Environment variable | Constructor parameter | |----------------------|---------------------------------------------------------------------------------|--------------------------------|-----------------------| -| **Metric namespace** | Logical container where all metrics will be placed e.g. `serverlessAirline` | `POWERTOOLS_METRICS_NAMESPACE` | `namespace` | | **Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `serviceName` | - -For a **complete list** of supported environment variables, refer to [this section](./../index.md#environment-variables). +| **Metric namespace** | Logical container where all metrics will be placed e.g. `serverlessAirline` | `POWERTOOLS_METRICS_NAMESPACE` | `namespace` | !!! tip Use your application name or main service as the metric namespace to easily group all metrics @@ -299,7 +297,7 @@ Using the Middy middleware or decorator will **automatically validate, serialize If you do not use the middleware or decorator, you have to flush your metrics manually. !!! warning "Metric validation" - If metrics are provided, and any of the following criteria are not met, a **`RangeError`** exception will be thrown: + If metrics are provided, and any of the following criteria are not met, a **`RangeError`** error will be thrown: * Maximum of 29 dimensions * Namespace is set only once (or none) diff --git a/docs/core/tracer.md b/docs/core/tracer.md index bba9442920..a63095fbcb 100644 --- a/docs/core/tracer.md +++ b/docs/core/tracer.md @@ -50,13 +50,13 @@ The `Tracer` utility must always be instantiated outside of the Lambda handler. The library has three optional settings. You can set them as environment variables, or pass them in the constructor: -Setting | Description | Environment variable | Constructor parameter -------------------------------------------------- |------------------------------------------------------------------------------------------------| ------------------------------------------------- | ------------------------------------------------- -**Tracing enabled** | Enables or disables tracing. By default tracing is enabled when running in AWS Lambda. | `POWERTOOLS_TRACE_ENABLED` | `enabled` -**Service name** | Sets an annotation with the **name of the service** across all traces e.g. `serverlessAirline` | `POWERTOOLS_SERVICE_NAME` | `serviceName` -**Capture HTTPs Requests** | Defines whether HTTPs requests will be traced or not, enabled by default when tracing is also enabled. | `POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS` | `captureHTTPsRequests` - -For a **complete list** of supported environment variables, refer to [this section](./../index.md#environment-variables). +| Setting | Description | Environment variable | Constructor parameter | +|----------------------------|-----------------------------------------------------------------------------------------------------------------| -------------------------------------------|------------------------| +| **Service name** | Sets an annotation with the **name of the service** across all traces e.g. `serverlessAirline` | `POWERTOOLS_SERVICE_NAME` | `serviceName` | +| **Tracing enabled** | Enables or disables tracing. By default tracing is enabled when running in AWS Lambda | `POWERTOOLS_TRACE_ENABLED` | `enabled` | +| **Capture HTTPs Requests** | Defines whether HTTPs requests will be traced or not, enabled by default when tracing is also enabled | `POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS` | `captureHTTPsRequests` | +| **Capture Response** | Defines whether functions responses are serialized as metadata, enabled by default when tracing is also enabled | `POWERTOOLS_TRACER_CAPTURE_RESPONSE` | `captureResult` | +| **Capture Errors** | Defines whether functions errors are serialized as metadata, enabled by default when tracing is also enabled | `POWERTOOLS_TRACER_CAPTURE_ERROR` | N/A | !!! note Before your use this utility, your AWS Lambda function must have [Active Tracing enabled](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html) as well as [have permissions](https://docs.aws.amazon.com/lambda/latest/dg/services-xray.html#services-xray-permissions) to send traces to AWS X-Ray @@ -476,13 +476,45 @@ Alternatively, use the `captureResponse: false` option in both `tracer.captureLa .use(captureLambdaHandler(tracer, { captureResponse: false })); ``` -### Disabling exception auto-capture +### Disabling errors auto-capture -Use **`POWERTOOLS_TRACER_CAPTURE_ERROR=false`** environment variable to instruct Tracer **not** to serialize exceptions as metadata. +Use **`POWERTOOLS_TRACER_CAPTURE_ERROR=false`** environment variable to instruct Tracer **not** to serialize errors as metadata. !!! info "Commonly useful in one scenario" - 1. You might **return sensitive** information from exceptions, stack traces you might not control + 1. You might **return sensitive** information from errors, stack traces you might not control + +### Access AWS X-Ray Root Trace ID + +Tracer exposes a `getRootXrayTraceId()` method that allows you to retrieve the [AWS X-Ray Root Trace ID](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces) corresponds to the current function execution. + +!!! info "This is commonly useful in two scenarios" + + 1. By including the root trace id in your response, consumers can use it to correlate requests + 2. You might want to surface the root trace id to your end users so that they can reference it while contacting customer service + +=== "index.ts" + + ```typescript hl_lines="9" + import { Tracer } from '@aws-lambda-powertools/tracer'; + + const tracer = new Tracer({ serviceName: 'serverlessAirline' }); + + export const handler = async (event: unknown, context: Context): Promise<void> => { + try { + ... + } catch (err) { + const rootTraceId = tracer.getRootXrayTraceId(); + + // Example of returning an error response + return { + statusCode: 500, + body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`, + headers: { "_X_AMZN_TRACE_ID": rootTraceId }, + }; + } + }; + ``` ### Escape hatch mechanism diff --git a/docs/index.md b/docs/index.md index 17b5a5f39d..9de2ce403c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,41 +3,31 @@ title: Homepage description: AWS Lambda Powertools for TypeScript --- -AWS Lambda Powertools for TypeScript provides a suite of utilities for AWS Lambda functions running on the Node.js runtime, to ease the adoption of best practices such as tracing, structured logging, custom metrics, and more. +A suite of utilities for AWS Lambda functions running on the Node.js runtime, to ease adopting best practices such as tracing, structured logging, custom metrics, [**and more**](#features). -You can use the library in both TypeScript and JavaScript code bases. +You can use Powertools in both TypeScript and JavaScript code bases. -## Tenets +???+ tip + Powertools is also available for [Python](https://awslabs.github.io/aws-lambda-powertools-python/){target="_blank"}, [Java](https://awslabs.github.io/aws-lambda-powertools-java/latest/){target="_blank"}, and [.NET](https://awslabs.github.io/aws-lambda-powertools-dotnet/){target="_blank"} -Core utilities such as Tracer, Logger, Metrics, and Event Handler will be available across all Lambda Powertools runtimes. Additional utilities are subjective to each language ecosystem and customer demand. +??? hint "Support this project by becoming a reference customer, sharing your work, or using Layers :heart:" -* **AWS Lambda only**. We optimise for AWS Lambda function environments and supported runtimes only. Utilities might work with web frameworks and non-Lambda environments, though they are not officially supported. -* **Eases the adoption of best practices**. The main priority of the utilities is to facilitate best practices adoption, as defined in the AWS Well-Architected Serverless Lens; all other functionality is optional. -* **Keep it lean**. Additional dependencies are carefully considered for security and ease of maintenance, and prevent negatively impacting startup time. -* **We strive for backwards compatibility**. New features and changes should keep backwards compatibility. If a breaking change cannot be avoided, the deprecation and migration process should be clearly defined. -* **We work backwards from the community**. We aim to strike a balance of what would work best for 80% of customers. Emerging practices are considered and discussed via Requests for Comment (RFCs) -* **Progressive**. Utilities are designed to be incrementally adoptable for customers at any stage of their Serverless journey. They follow language idioms and their community’s common practices. - -## Features + You can choose to support us in three ways: -| Utility | Description -| ------------------------------------------------- | --------------------------------------------------------------------------------- -[Tracer](./core/tracer.md) | Trace Lambda function handlers, and both synchronous and asynchronous functions -[Logger](./core/logger.md) | Structured logging made easier, and a middleware to enrich log items with key details of the Lambda context -[Metrics](./core/metrics.md) | Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF) + 1) [**Become a reference customers**](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/new?assignees=&labels=customer-reference&template=support_powertools.yml&title=%5BSupport+Lambda+Powertools%5D%3A+%3Cyour+organization+name%3E). This gives us permission to list your company in our documentation. -## Installation + 2) [**Share your work**](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/new?assignees=&labels=community-content&template=share_your_work.yml&title=%5BI+Made+This%5D%3A+%3CTITLE%3E). Blog posts, video, sample projects you used Powertools! -You can use Powertools through [AWS Lambda Layer](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-layer) or install it as your dependency via NPM: + 3) Use [**Lambda Layers**](#lambda-layer), if possible. This helps us understand who uses Powertools in a non-intrusive way, and helps us gain future investments for other Lambda Powertools languages. -* **Lambda Layer**: [**arn:aws:lambda:{region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:2**](#){: .copyMe}:clipboard: -* **NPM**: **`npm install @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics @aws-lambda-powertools/logger`** + When using Layers, you can add Lambda Powertools as a `devDependency` to not impact the development process. -???+ hint "Support this project by using Lambda Layers :heart:" - Lambda Layers allow us to understand who uses this library in a non-intrusive way. This helps us justify and gain future investments for other Lambda Powertools languages. +## Install - When using Layers, you can add Lambda Powertools as a dev dependency to not impact the development process. +Powertools is available in the following formats: +* **Lambda Layer**: [**arn:aws:lambda:{region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3**](#){: .copyMe}:clipboard: +* **npm**: **`npm install @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics @aws-lambda-powertools/logger`** ### Lambda Layer @@ -45,233 +35,219 @@ You can use Powertools through [AWS Lambda Layer](https://docs.aws.amazon.com/la You can include Lambda Powertools Lambda Layer using [AWS Lambda Console](https://docs.aws.amazon.com/lambda/latest/dg/invocation-layers.html#invocation-layers-using){target="_blank"}, or your preferred deployment framework. -??? note "Note: Expand to copy any regional Lambda Layer ARN" +??? note "Note: Click to expand and copy any regional Lambda Layer ARN" | Region | Layer ARN |--------------------------- | --------------------------- - | `us-east-1` | [arn:aws:lambda:us-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `us-east-2` | [arn:aws:lambda:us-east-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `us-west-1` | [arn:aws:lambda:us-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `us-west-2` | [arn:aws:lambda:us-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ap-south-1` | [arn:aws:lambda:ap-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ap-northeast-1` | [arn:aws:lambda:ap-northeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ap-northeast-2` | [arn:aws:lambda:ap-northeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ap-northeast-3` | [arn:aws:lambda:ap-northeast-3:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ap-southeast-1` | [arn:aws:lambda:ap-southeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ap-southeast-2` | [arn:aws:lambda:ap-southeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `eu-central-1` | [arn:aws:lambda:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `eu-west-1` | [arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `eu-west-2` | [arn:aws:lambda:eu-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `eu-west-3` | [arn:aws:lambda:eu-west-3:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `eu-north-1` | [arn:aws:lambda:eu-north-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `ca-central-1` | [arn:aws:lambda:ca-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - | `sa-east-1` | [arn:aws:lambda:sa-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2](#){: .copyMe}:clipboard: - -??? question "Can't find our Lambda Layer for your preferred AWS region?" - You can use our [CDK Layer Construct](https://github.com/aws-samples/cdk-lambda-powertools-python-layer){target="_blank"}, or NPM like you normally would for any other library. - - Please do file a feature request with the region you'd want us to prioritize making our Lambda Layer available. - -=== "SAM" - - ```yaml hl_lines="5" - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Layers: - - !Sub arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:2 - ``` - -=== "Serverless framework" - - ```yaml hl_lines="5" - functions: - hello: - handler: lambda_function.lambda_handler - layers: - - arn:aws:lambda:${aws:region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:2 - ``` - -=== "CDK" - - ```typescript hl_lines="11 16" - import * as cdk from 'aws-cdk-lib'; - import { Construct } from 'constructs'; - import * as lambda from 'aws-cdk-lib/aws-lambda'; - export class SampleFunctionWithLayer extends Construct { - constructor(scope: Construct, id: string) { - super(scope, id); - // Create a Layer with AWS Lambda Powertools for TypeScript - const powertoolsLayer = lambda.LayerVersion.fromLayerVersionArn( - this, - 'PowertoolsLayer', - `arn:aws:lambda:${cdk.Stack.of(this).region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:2` - ); - new lambda.Function(this, 'Function', { - runtime: lambda.Runtime.NODEJS_16_X, - // Add the Layer to a Lambda function - layers: [powertoolsLayer], - code: lambda.Code.fromInline(` - const { Logger } = require('@aws-lambda-powertools/logger'); - const { Metrics } = require('@aws-lambda-powertools/metrics'); - const { Tracer } = require('@aws-lambda-powertools/tracer'); - const logger = new Logger({logLevel: 'DEBUG'}); - const metrics = new Metrics(); - const tracer = new Tracer(); - exports.handler = function(event, ctx) { - logger.debug("Hello World!"); - }`), - handler: 'index.handler', - }); - } - } - ``` - -=== "Terraform" - - ```terraform hl_lines="9 38" - terraform { - required_version = "~> 1.0.5" - required_providers { - aws = "~> 3.50.0" - } - } - provider "aws" { - region = "{region}" - } - resource "aws_iam_role" "iam_for_lambda" { - name = "iam_for_lambda" - assume_role_policy = <<EOF - { - "Version": "2012-10-17", - "Statement": [ - { - "Action": "sts:AssumeRole", - "Principal": { - "Service": "lambda.amazonaws.com" - }, - "Effect": "Allow" - } - ] - } - EOF - } - resource "aws_lambda_function" "test_lambda" { - filename = "lambda_function_payload.zip" - function_name = "lambda_function_name" - role = aws_iam_role.iam_for_lambda.arn - handler = "index.test" - runtime = "nodejs16.x" - layers = ["arn:aws:lambda:{region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:2"] - source_code_hash = filebase64sha256("lambda_function_payload.zip") - } - ``` - -=== "Amplify" - - ```zsh - # 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:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2 - ❯ 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:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:2 - ? Do you want to edit the local lambda function now? No - ``` - -=== "Get the Layer .zip contents" - Change `{region}` to your AWS region, e.g. `eu-west-1` - - ```bash title="AWS CLI" - aws lambda get-layer-version-by-arn --arn arn:aws:lambda:{region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:2 --region {region} - ``` - - The pre-signed URL to download this Lambda Layer will be within `Location` key. - -???+ warning "Warning: Limitations" - - Container Image deployment (OCI) or inline Lambda functions do not support Lambda Layers. - -If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools` from being bundled since the packages will be brought by the Layer: - -=== "SAM" (check the [doc](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build-typescript.html) for more details) - - ```yaml hl_lines="5" - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: + | `us-east-1` | [arn:aws:lambda:us-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `us-east-2` | [arn:aws:lambda:us-east-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `us-west-1` | [arn:aws:lambda:us-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `us-west-2` | [arn:aws:lambda:us-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ap-south-1` | [arn:aws:lambda:ap-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ap-northeast-1` | [arn:aws:lambda:ap-northeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ap-northeast-2` | [arn:aws:lambda:ap-northeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ap-northeast-3` | [arn:aws:lambda:ap-northeast-3:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ap-southeast-1` | [arn:aws:lambda:ap-southeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ap-southeast-2` | [arn:aws:lambda:ap-southeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `eu-central-1` | [arn:aws:lambda:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `eu-west-1` | [arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `eu-west-2` | [arn:aws:lambda:eu-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `eu-west-3` | [arn:aws:lambda:eu-west-3:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `eu-north-1` | [arn:aws:lambda:eu-north-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `ca-central-1` | [arn:aws:lambda:ca-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + | `sa-east-1` | [arn:aws:lambda:sa-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScript:3](#){: .copyMe}:clipboard: + +??? note "Note: Click to expand and copy code snippets for popular frameworks" + + === "SAM" + + ```yaml hl_lines="5" + MyLambdaFunction: + Type: AWS::Serverless::Function + Properties: + Layers: + - !Sub arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3 + ``` + + If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools` from being bundled since the packages will be already present the Layer: + + ```yaml hl_lines="5" + MyLambdaFunction: + Type: AWS::Serverless::Function + Properties: ... Metadata: # Manage esbuild properties BuildMethod: esbuild BuildProperties: - Minify: true - External: + Minify: true + External: - '@aws-lambda-powertools/commons' - '@aws-lambda-powertools/logger' - '@aws-lambda-powertools/metrics' - '@aws-lambda-powertools/tracer' - ``` - -=== "Serverless framework (check the [doc](https://floydspace.github.io/serverless-esbuild/) for more details)" - - ```yaml hl_lines="5" - custom: - esbuild: - external: - - '@aws-lambda-powertools/commons' - - '@aws-lambda-powertools/logger' - - '@aws-lambda-powertools/metrics' - - '@aws-lambda-powertools/tracer' - ``` - -=== "CDK (check the [doc](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.BundlingOptions.html#externalmodules) for more details)" - - ```typescript hl_lines="11 16" - new awsLambdaNodejs.NodejsFunction(this, 'Function', { - ... - bundling: { - externalModules: [ - '@aws-lambda-powertools/commons', - '@aws-lambda-powertools/logger', - '@aws-lambda-powertools/metrics', - '@aws-lambda-powertools/tracer', - ], - } + ``` + + Check the [documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build-typescript.html) for more details. + + === "Serverless framework" + + ```yaml hl_lines="5" + functions: + hello: + handler: lambda_function.lambda_handler + layers: + - arn:aws:lambda:${aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3 + ``` + + If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools` from being bundled since the packages will be already present the Layer: + + ```yaml + custom: + esbuild: + external: + - '@aws-lambda-powertools/commons' + - '@aws-lambda-powertools/logger' + - '@aws-lambda-powertools/metrics' + - '@aws-lambda-powertools/tracer' + ``` + + Check the [documentation](https://floydspace.github.io/serverless-esbuild/) for more details. + + === "CDK" + + ```typescript hl_lines="13 19" + import * as cdk from 'aws-cdk-lib'; + import { Construct } from 'constructs'; + import * as lambda from 'aws-cdk-lib/aws-lambda'; + + export class SampleFunctionWithLayer extends Construct { + constructor(scope: Construct, id: string) { + super(scope, id); + + // Create a Layer with AWS Lambda Powertools for TypeScript + const powertoolsLayer = lambda.LayerVersion.fromLayerVersionArn( + this, + 'PowertoolsLayer', + `arn:aws:lambda:${cdk.Stack.of(this).region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3` + ); + + new lambda.Function(this, 'Function', { + runtime: lambda.Runtime.NODEJS_16_X, + // Add the Layer to a Lambda function + layers: [powertoolsLayer], + code: lambda.Code.fromInline(`...`), + handler: 'index.handler', }); - ``` - -### NPM Modules - -The AWS Lambda Powertools for TypeScript utilities (which from here will be referred as Powertools) follow a modular approach, similar to the official [AWS SDK v3 for JavaScript](https://github.com/aws/aws-sdk-js-v3). -Each TypeScript utility is installed as standalone NPM package. - -Install all three core utilities at once with this single command: - -```shell -npm install @aws-lambda-powertools/logger @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics -``` + } + } + ``` + + If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools` from being bundled since the packages will be already present the Layer: + + ```typescript + new awsLambdaNodejs.NodejsFunction(this, 'Function', { + ... + bundling: { + externalModules: [ + '@aws-lambda-powertools/commons', + '@aws-lambda-powertools/logger', + '@aws-lambda-powertools/metrics', + '@aws-lambda-powertools/tracer', + ], + } + }); + ``` + + Check the [documentation](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.BundlingOptions.html#externalmodules) for more details. + + === "Terraform" + + ```terraform hl_lines="9 36" + terraform { + required_version = "~> 1.0.5" + required_providers { + aws = "~> 3.50.0" + } + } + provider "aws" { + region = "{aws::region}" + } -Or refer to the installation guide of each utility: + resource "aws_lambda_function" "test_lambda" { + filename = "lambda_function_payload.zip" + function_name = "lambda_function_name" + role = ... + handler = "index.handler" + runtime = "nodejs16.x" + layers = ["arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3"] + source_code_hash = filebase64sha256("lambda_function_payload.zip") + } + ``` + + === "Pulumi" + + ```typescript hl_lines="11" + import * as pulumi from "@pulumi/pulumi"; + import * as aws from "@pulumi/aws"; + + const role = new aws.iam.Role("role", { + assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal(aws.iam.Principals.LambdaPrincipal), + managedPolicyArns: [aws.iam.ManagedPolicies.AWSLambdaBasicExecutionRole] + }); + + const lambdaFunction = new aws.lambda.Function("function", { + layers: [ + pulumi.interpolate`arn:aws:lambda:${aws.getRegionOutput().name}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3` + ], + code: new pulumi.asset.FileArchive("lambda_function_payload.zip"), + tracingConfig: { + mode: "Active" + }, + runtime: aws.lambda.Runtime.NodeJS16dX, + handler: "index.handler", + role: role.arn, + architectures: ["x86_64"] + }); + ``` + + === "Amplify" + + ```zsh + # 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:AWSLambdaPowertoolsTypeScript:3 + ❯ 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:AWSLambdaPowertoolsTypeScript:3 + ? Do you want to edit the local lambda function now? No + ``` + + === "Get the Layer .zip contents" + ```bash title="AWS CLI" + aws lambda get-layer-version-by-arn --arn arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScript:3 --region {region} + ``` + + The pre-signed URL to download this Lambda Layer will be within `Location` key. -[Installation guide for the **Tracer** utility](./core/tracer.md#getting-started) +???+ warning "Warning: Limitations" -[Installation guide for the **Logger** utility](./core/logger.md#getting-started) + Container Image deployment (OCI) or inline Lambda functions do not support Lambda Layers. -[Installation guide for the **Metrics** utility](./core/metrics.md#getting-started) ## Instrumentation @@ -283,10 +259,29 @@ You can instrument your code with Powertools in three different ways: The examples in this documentation will feature all the approaches described above, when applicable. +## Examples + +The project's repository includes examples of how to instrument your functions both in AWS CDK and AWS SAM: + +* [AWS CDK](https://github.com/awslabs/aws-lambda-powertools-typescript/tree/main/examples/cdk){target="_blank"} +* [AWS SAM](https://github.com/awslabs/aws-lambda-powertools-typescript/tree/main/examples/sam){target="_blank"} + +If instead you want to see Powertools for TypeScript in a slightly more complex use case, check the [Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo). You can find instructions on how to deploy and load test this application in the [repository](https://github.com/aws-samples/serverless-typescript-demo). + +## Features + +Core utilities such as Tracing, Logging, and Metrics will be available across all Lambda Powertools languages. Additional utilities are subjective to each language ecosystem and customer demand. + +| Utility | Description | +| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| [Tracer](./core/tracer.md) | Decorators and utilities to trace Lambda function handlers, and both synchronous and asynchronous functions | +| [Logger](./core/logger.md) | Structured logging made easier, and a middleware to enrich structured logging with key Lambda context details | +| [Metrics](./core/metrics.md) | Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF) | + ## Environment variables -!!! info - **Explicit parameters passed in constructors or in middleware/decorators take precedence over environment variables.** +???+ info + Explicit parameters take precedence over environment variables | Environment variable | Description | Utility | Default | |----------------------------------------------|----------------------------------------------------------------------------------------|---------------------------|-----------------------| @@ -300,35 +295,14 @@ The examples in this documentation will feature all the approaches described abo | **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logger](./core/logger) | `0` | | **LOG_LEVEL** | Sets logging level | [Logger](./core/logger) | `INFO` | -## Examples - -* [CDK](https://github.com/awslabs/aws-lambda-powertools-typescript/tree/main/examples/cdk){target="_blank"} -* [SAM](https://github.com/awslabs/aws-lambda-powertools-typescript/tree/main/examples/sam){target="_blank"} - -## Serverless TypeScript demo application - -The [Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo) shows how to use Lambda Powertools for TypeScript. -You can find instructions on how to deploy and load test this application in the [repository](https://github.com/aws-samples/serverless-typescript-demo). - -## Contribute - -If you are interested in contributing to this project, please refer to our [Contributing Guidelines](https://github.com/awslabs/aws-lambda-powertools-typescript/blob/main/CONTRIBUTING.md). - -## Roadmap - -The roadmap of Powertools is driven by customers’ demand. -Help us prioritize upcoming functionalities or utilities by [upvoting existing RFCs and feature requests](https://github.com/awslabs/aws-lambda-powertools-typescript/issues), or [creating new ones](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/new/choose), in this GitHub repository. - -## Connect - -* **AWS Lambda Powertools on Discord**: `#typescript` - **[Invite link](https://discord.gg/B8zZKbbyET){target="_blank"}** -* **Email**: aws-lambda-powertools-feedback@amazon.com - -## Credits - -Credits for the Lambda Powertools idea go to [DAZN](https://github.com/getndazn){target="_blank"} and their [DAZN Lambda Powertools](https://github.com/getndazn/dazn-lambda-powertools/){target="_blank"}. - -## License +## Tenets -This library is licensed under the MIT-0 License. See the [LICENSE](https://github.com/awslabs/aws-lambda-powertools-typescript/blob/main/LICENSE) file. +These are our core principles to guide our decision making. +* **AWS Lambda only**. We optimise for AWS Lambda function environments and supported runtimes only. Utilities might work with web frameworks and non-Lambda environments, though they are not officially supported. +* **Eases the adoption of best practices**. The main priority of the utilities is to facilitate best practices adoption, as defined in the AWS Well-Architected Serverless Lens; all other functionality is optional. +* **Keep it lean**. Additional dependencies are carefully considered for security and ease of maintenance, and prevent negatively impacting startup time. +* **We strive for backwards compatibility**. New features and changes should keep backwards compatibility. If a breaking change cannot be avoided, the deprecation and migration process should be clearly defined. +* **We work backwards from the community**. We aim to strike a balance of what would work best for 80% of customers. Emerging practices are considered and discussed via Requests for Comment (RFCs) +* **Progressive**. Utilities are designed to be incrementally adoptable for customers at any stage of their Serverless journey. They follow language idioms and their community’s common practices. + \ No newline at end of file diff --git a/examples/cdk/CHANGELOG.md b/examples/cdk/CHANGELOG.md index 228e2d67e2..c95e0c7e15 100644 --- a/examples/cdk/CHANGELOG.md +++ b/examples/cdk/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + +**Note:** Version bump only for package cdk-app + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/examples/cdk/package-lock.json b/examples/cdk/package-lock.json index 3714ac5a2d..e8ee959448 100644 --- a/examples/cdk/package-lock.json +++ b/examples/cdk/package-lock.json @@ -1,17 +1,17 @@ { "name": "cdk-app", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "cdk-app", - "version": "1.3.0", + "version": "1.4.0", "license": "MIT-0", "dependencies": { - "@aws-lambda-powertools/logger": "^1.2.1", - "@aws-lambda-powertools/metrics": "^1.2.1", - "@aws-lambda-powertools/tracer": "^1.2.1", + "@aws-lambda-powertools/logger": "^1.3.0", + "@aws-lambda-powertools/metrics": "^1.3.0", + "@aws-lambda-powertools/tracer": "^1.3.0", "@aws-sdk/client-sts": "^3.53.0", "@middy/core": "^2.5.6", "@types/aws-lambda": "^8.10.86", @@ -123,35 +123,35 @@ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" }, "node_modules/@aws-lambda-powertools/commons": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.2.1.tgz", - "integrity": "sha512-wHdAgzXQfRqcm6kIuxrQjKL8x02sVTMc7rcMJPkHU1DsGNL7Z3g0H+tkrlmFimGkRqPv724J2OqNdEvBJKaoMQ==" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.3.0.tgz", + "integrity": "sha512-DYQDa7/TlIt/BrpwSyOFIvcx1uj265+d3wkOKvyYIsDN5J3wX9jo1bdt7LsoCFVGw55zY4kE4W6WC+vuKk9DXw==" }, "node_modules/@aws-lambda-powertools/logger": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.2.1.tgz", - "integrity": "sha512-Yb9uOi49h7yOut/NujnHjTd+sP4nBMsnuxMIsNtKvBFZ2ftaPlGAfqOdevqC3ImcIXlyiypxXd1gQmEMq3uJ8Q==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.3.0.tgz", + "integrity": "sha512-QBRAU/2XZAmDF+BY+WEiSF7CI5OBoK6kaks8696dMBpepLK/LtHlEC40a30YBvlg6W7ttcjjyaWcP2BnA3F5fw==", "dependencies": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "lodash.clonedeep": "^4.5.0", "lodash.merge": "^4.6.2", "lodash.pickby": "^4.6.0" } }, "node_modules/@aws-lambda-powertools/metrics": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.2.1.tgz", - "integrity": "sha512-X0B0rkepFoeiq+l5AQpnOR+qT+Fr6tzc22RxhPc6IB3Lz+QNdory4i+w9ToSUEDrS0Lls77hlHNoEHeuW7H12w==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.3.0.tgz", + "integrity": "sha512-9EW0yTZEfhUZiGN7x22s4DJYTWt1JY8iURcAwZoVUPj0knxLdcgUUuex/HzRQv3HaMYD94L8eCr0noS7/FZ0RQ==", "dependencies": { - "@aws-lambda-powertools/commons": "^1.2.1" + "@aws-lambda-powertools/commons": "^1.3.0" } }, "node_modules/@aws-lambda-powertools/tracer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.2.1.tgz", - "integrity": "sha512-OPhb887RabgKYgKS2B5sAu+8o5r9VuLoz3sNyFsIp1GyCue4aswAevuGRUo0sJkJlhHvi1beTh2/QqQQzWd5iA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.3.0.tgz", + "integrity": "sha512-j1/OrnBhiFqB2mwmgDvlomDeP16dNbE9D9yHqfo0LMZyDCms6LU8D/2DZdIDYht1QB9aLgxZeEYoLGaR+COypg==", "dependencies": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "aws-xray-sdk-core": "^3.3.6" } }, @@ -6731,35 +6731,35 @@ } }, "@aws-lambda-powertools/commons": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.2.1.tgz", - "integrity": "sha512-wHdAgzXQfRqcm6kIuxrQjKL8x02sVTMc7rcMJPkHU1DsGNL7Z3g0H+tkrlmFimGkRqPv724J2OqNdEvBJKaoMQ==" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.3.0.tgz", + "integrity": "sha512-DYQDa7/TlIt/BrpwSyOFIvcx1uj265+d3wkOKvyYIsDN5J3wX9jo1bdt7LsoCFVGw55zY4kE4W6WC+vuKk9DXw==" }, "@aws-lambda-powertools/logger": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.2.1.tgz", - "integrity": "sha512-Yb9uOi49h7yOut/NujnHjTd+sP4nBMsnuxMIsNtKvBFZ2ftaPlGAfqOdevqC3ImcIXlyiypxXd1gQmEMq3uJ8Q==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.3.0.tgz", + "integrity": "sha512-QBRAU/2XZAmDF+BY+WEiSF7CI5OBoK6kaks8696dMBpepLK/LtHlEC40a30YBvlg6W7ttcjjyaWcP2BnA3F5fw==", "requires": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "lodash.clonedeep": "^4.5.0", "lodash.merge": "^4.6.2", "lodash.pickby": "^4.6.0" } }, "@aws-lambda-powertools/metrics": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.2.1.tgz", - "integrity": "sha512-X0B0rkepFoeiq+l5AQpnOR+qT+Fr6tzc22RxhPc6IB3Lz+QNdory4i+w9ToSUEDrS0Lls77hlHNoEHeuW7H12w==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.3.0.tgz", + "integrity": "sha512-9EW0yTZEfhUZiGN7x22s4DJYTWt1JY8iURcAwZoVUPj0knxLdcgUUuex/HzRQv3HaMYD94L8eCr0noS7/FZ0RQ==", "requires": { - "@aws-lambda-powertools/commons": "^1.2.1" + "@aws-lambda-powertools/commons": "^1.3.0" } }, "@aws-lambda-powertools/tracer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.2.1.tgz", - "integrity": "sha512-OPhb887RabgKYgKS2B5sAu+8o5r9VuLoz3sNyFsIp1GyCue4aswAevuGRUo0sJkJlhHvi1beTh2/QqQQzWd5iA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.3.0.tgz", + "integrity": "sha512-j1/OrnBhiFqB2mwmgDvlomDeP16dNbE9D9yHqfo0LMZyDCms6LU8D/2DZdIDYht1QB9aLgxZeEYoLGaR+COypg==", "requires": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "aws-xray-sdk-core": "^3.3.6" } }, diff --git a/examples/cdk/package.json b/examples/cdk/package.json index 9784881e78..02e8f9504f 100644 --- a/examples/cdk/package.json +++ b/examples/cdk/package.json @@ -1,6 +1,6 @@ { "name": "cdk-app", - "version": "1.3.0", + "version": "1.4.0", "author": { "name": "Amazon Web Services", "url": "https://aws.amazon.com" @@ -34,9 +34,9 @@ "typescript": "^4.1.3" }, "dependencies": { - "@aws-lambda-powertools/logger": "^1.2.1", - "@aws-lambda-powertools/metrics": "^1.2.1", - "@aws-lambda-powertools/tracer": "^1.2.1", + "@aws-lambda-powertools/logger": "^1.3.0", + "@aws-lambda-powertools/metrics": "^1.3.0", + "@aws-lambda-powertools/tracer": "^1.3.0", "@aws-sdk/client-sts": "^3.53.0", "@middy/core": "^2.5.6", "@types/aws-lambda": "^8.10.86", diff --git a/examples/sam/CHANGELOG.md b/examples/sam/CHANGELOG.md index f9f717db62..ea68d8f58e 100644 --- a/examples/sam/CHANGELOG.md +++ b/examples/sam/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + +**Note:** Version bump only for package powertools-typescript-sam-example + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/examples/sam/package-lock.json b/examples/sam/package-lock.json index c1edda4323..29cfcdfdbf 100644 --- a/examples/sam/package-lock.json +++ b/examples/sam/package-lock.json @@ -1,17 +1,17 @@ { "name": "powertools-typescript-sam-example", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "powertools-typescript-sam-example", - "version": "1.3.0", + "version": "1.4.0", "license": "MIT-0", "dependencies": { - "@aws-lambda-powertools/logger": "^1.2.1", - "@aws-lambda-powertools/metrics": "^1.2.1", - "@aws-lambda-powertools/tracer": "^1.2.1", + "@aws-lambda-powertools/logger": "^1.3.0", + "@aws-lambda-powertools/metrics": "^1.3.0", + "@aws-lambda-powertools/tracer": "^1.3.0", "aws-sdk": "^2.1122.0" }, "devDependencies": { @@ -40,35 +40,35 @@ } }, "node_modules/@aws-lambda-powertools/commons": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.2.1.tgz", - "integrity": "sha512-wHdAgzXQfRqcm6kIuxrQjKL8x02sVTMc7rcMJPkHU1DsGNL7Z3g0H+tkrlmFimGkRqPv724J2OqNdEvBJKaoMQ==" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.3.0.tgz", + "integrity": "sha512-DYQDa7/TlIt/BrpwSyOFIvcx1uj265+d3wkOKvyYIsDN5J3wX9jo1bdt7LsoCFVGw55zY4kE4W6WC+vuKk9DXw==" }, "node_modules/@aws-lambda-powertools/logger": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.2.1.tgz", - "integrity": "sha512-Yb9uOi49h7yOut/NujnHjTd+sP4nBMsnuxMIsNtKvBFZ2ftaPlGAfqOdevqC3ImcIXlyiypxXd1gQmEMq3uJ8Q==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.3.0.tgz", + "integrity": "sha512-QBRAU/2XZAmDF+BY+WEiSF7CI5OBoK6kaks8696dMBpepLK/LtHlEC40a30YBvlg6W7ttcjjyaWcP2BnA3F5fw==", "dependencies": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "lodash.clonedeep": "^4.5.0", "lodash.merge": "^4.6.2", "lodash.pickby": "^4.6.0" } }, "node_modules/@aws-lambda-powertools/metrics": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.2.1.tgz", - "integrity": "sha512-X0B0rkepFoeiq+l5AQpnOR+qT+Fr6tzc22RxhPc6IB3Lz+QNdory4i+w9ToSUEDrS0Lls77hlHNoEHeuW7H12w==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.3.0.tgz", + "integrity": "sha512-9EW0yTZEfhUZiGN7x22s4DJYTWt1JY8iURcAwZoVUPj0knxLdcgUUuex/HzRQv3HaMYD94L8eCr0noS7/FZ0RQ==", "dependencies": { - "@aws-lambda-powertools/commons": "^1.2.1" + "@aws-lambda-powertools/commons": "^1.3.0" } }, "node_modules/@aws-lambda-powertools/tracer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.2.1.tgz", - "integrity": "sha512-OPhb887RabgKYgKS2B5sAu+8o5r9VuLoz3sNyFsIp1GyCue4aswAevuGRUo0sJkJlhHvi1beTh2/QqQQzWd5iA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.3.0.tgz", + "integrity": "sha512-j1/OrnBhiFqB2mwmgDvlomDeP16dNbE9D9yHqfo0LMZyDCms6LU8D/2DZdIDYht1QB9aLgxZeEYoLGaR+COypg==", "dependencies": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "aws-xray-sdk-core": "^3.3.6" } }, @@ -5419,35 +5419,35 @@ } }, "@aws-lambda-powertools/commons": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.2.1.tgz", - "integrity": "sha512-wHdAgzXQfRqcm6kIuxrQjKL8x02sVTMc7rcMJPkHU1DsGNL7Z3g0H+tkrlmFimGkRqPv724J2OqNdEvBJKaoMQ==" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/commons/-/commons-1.3.0.tgz", + "integrity": "sha512-DYQDa7/TlIt/BrpwSyOFIvcx1uj265+d3wkOKvyYIsDN5J3wX9jo1bdt7LsoCFVGw55zY4kE4W6WC+vuKk9DXw==" }, "@aws-lambda-powertools/logger": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.2.1.tgz", - "integrity": "sha512-Yb9uOi49h7yOut/NujnHjTd+sP4nBMsnuxMIsNtKvBFZ2ftaPlGAfqOdevqC3ImcIXlyiypxXd1gQmEMq3uJ8Q==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/logger/-/logger-1.3.0.tgz", + "integrity": "sha512-QBRAU/2XZAmDF+BY+WEiSF7CI5OBoK6kaks8696dMBpepLK/LtHlEC40a30YBvlg6W7ttcjjyaWcP2BnA3F5fw==", "requires": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "lodash.clonedeep": "^4.5.0", "lodash.merge": "^4.6.2", "lodash.pickby": "^4.6.0" } }, "@aws-lambda-powertools/metrics": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.2.1.tgz", - "integrity": "sha512-X0B0rkepFoeiq+l5AQpnOR+qT+Fr6tzc22RxhPc6IB3Lz+QNdory4i+w9ToSUEDrS0Lls77hlHNoEHeuW7H12w==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/metrics/-/metrics-1.3.0.tgz", + "integrity": "sha512-9EW0yTZEfhUZiGN7x22s4DJYTWt1JY8iURcAwZoVUPj0knxLdcgUUuex/HzRQv3HaMYD94L8eCr0noS7/FZ0RQ==", "requires": { - "@aws-lambda-powertools/commons": "^1.2.1" + "@aws-lambda-powertools/commons": "^1.3.0" } }, "@aws-lambda-powertools/tracer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.2.1.tgz", - "integrity": "sha512-OPhb887RabgKYgKS2B5sAu+8o5r9VuLoz3sNyFsIp1GyCue4aswAevuGRUo0sJkJlhHvi1beTh2/QqQQzWd5iA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@aws-lambda-powertools/tracer/-/tracer-1.3.0.tgz", + "integrity": "sha512-j1/OrnBhiFqB2mwmgDvlomDeP16dNbE9D9yHqfo0LMZyDCms6LU8D/2DZdIDYht1QB9aLgxZeEYoLGaR+COypg==", "requires": { - "@aws-lambda-powertools/commons": "^1.2.1", + "@aws-lambda-powertools/commons": "^1.3.0", "aws-xray-sdk-core": "^3.3.6" } }, diff --git a/examples/sam/package.json b/examples/sam/package.json index 55b0ea1dd9..a213ce570a 100644 --- a/examples/sam/package.json +++ b/examples/sam/package.json @@ -1,6 +1,6 @@ { "name": "powertools-typescript-sam-example", - "version": "1.3.0", + "version": "1.4.0", "author": { "name": "Amazon Web Services", "url": "https://aws.amazon.com" @@ -30,9 +30,9 @@ "typescript": "^4.1.3" }, "dependencies": { - "@aws-lambda-powertools/logger": "^1.2.1", - "@aws-lambda-powertools/metrics": "^1.2.1", - "@aws-lambda-powertools/tracer": "^1.2.1", + "@aws-lambda-powertools/logger": "^1.3.0", + "@aws-lambda-powertools/metrics": "^1.3.0", + "@aws-lambda-powertools/tracer": "^1.3.0", "aws-sdk": "^2.1122.0" } } diff --git a/layer-publisher/CHANGELOG.md b/layer-publisher/CHANGELOG.md index b3231c037c..1aac696179 100644 --- a/layer-publisher/CHANGELOG.md +++ b/layer-publisher/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + + +### Features + +* **all:** moved EnvService to commons + exposed getXrayTraceId in tracer ([#1123](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1123)) ([c8e3c15](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/c8e3c15b64142ebe6f43835a5917ecba26293a32)) + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/layer-publisher/package-lock.json b/layer-publisher/package-lock.json index 12c0094d75..185cbc4d8a 100644 --- a/layer-publisher/package-lock.json +++ b/layer-publisher/package-lock.json @@ -1,6 +1,6 @@ { "name": "layer-publisher", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 2, "requires": true, "packages": { diff --git a/layer-publisher/package.json b/layer-publisher/package.json index 2aaae9b124..d1fe56514b 100644 --- a/layer-publisher/package.json +++ b/layer-publisher/package.json @@ -1,6 +1,6 @@ { "name": "layer-publisher", - "version": "1.3.0", + "version": "1.4.0", "bin": { "layer-publisher": "bin/layer-publisher.js" }, diff --git a/layer-publisher/tests/unit/__snapshots__/layer-publisher.test.ts.snap b/layer-publisher/tests/unit/__snapshots__/layer-publisher.test.ts.snap index 161eb78d35..9e6b8f7ad7 100644 --- a/layer-publisher/tests/unit/__snapshots__/layer-publisher.test.ts.snap +++ b/layer-publisher/tests/unit/__snapshots__/layer-publisher.test.ts.snap @@ -32,7 +32,7 @@ Object { "S3Bucket": Object { "Fn::Sub": "cdk-hnb659fds-assets-\${AWS::AccountId}-\${AWS::Region}", }, - "S3Key": "c2f621503b147cecccf2e6cc6df420a8f11ee29ae042d2c1f523cf5db3f47ca2.zip", + "S3Key": "dbdb3f66eaeed03649521bf73dbcdd95a713086afccbac3f57fa407ffb76bdaa.zip", }, "Description": "Lambda Powertools for TypeScript version 1.0.1", "LayerName": "AWSLambdaPowertoolsTypeScript", diff --git a/lerna.json b/lerna.json index 2502a624f1..6a04c6184f 100644 --- a/lerna.json +++ b/lerna.json @@ -8,7 +8,7 @@ "examples/sam", "layer-publisher" ], - "version": "1.3.0", + "version": "1.4.0", "npmClient": "npm", "message": "chore(release): %s [skip ci]" } \ No newline at end of file diff --git a/packages/commons/CHANGELOG.md b/packages/commons/CHANGELOG.md index a3e0a202c8..d0ea826fbe 100644 --- a/packages/commons/CHANGELOG.md +++ b/packages/commons/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + + +### Features + +* **all:** moved EnvService to commons + exposed getXrayTraceId in tracer ([#1123](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1123)) ([c8e3c15](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/c8e3c15b64142ebe6f43835a5917ecba26293a32)) + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/packages/commons/package.json b/packages/commons/package.json index 4eb20766e3..f9578c0032 100644 --- a/packages/commons/package.json +++ b/packages/commons/package.json @@ -1,6 +1,6 @@ { "name": "@aws-lambda-powertools/commons", - "version": "1.3.0", + "version": "1.4.0", "description": "A shared utility package for AWS Lambda Powertools for TypeScript libraries", "author": { "name": "Amazon Web Services", diff --git a/packages/commons/src/config/ConfigService.ts b/packages/commons/src/config/ConfigService.ts new file mode 100644 index 0000000000..6e8f4adf6b --- /dev/null +++ b/packages/commons/src/config/ConfigService.ts @@ -0,0 +1,31 @@ +/** + * Abstract class ConfigService + * + * This class defines common methods and variables that can be set by the developer + * in the runtime. + * + * @class + * @abstract + */ +abstract class ConfigService { + + /** + * It returns the value of an environment variable that has given name. + * + * @param {string} name + * @returns {string} + */ + public abstract get(name: string): string; + + /** + * It returns the value of the POWERTOOLS_SERVICE_NAME environment variable. + * + * @returns {string} + */ + public abstract getServiceName(): string; + +} + +export { + ConfigService, +}; \ No newline at end of file diff --git a/packages/commons/src/config/EnvironmentVariablesService.ts b/packages/commons/src/config/EnvironmentVariablesService.ts new file mode 100644 index 0000000000..380bbc0458 --- /dev/null +++ b/packages/commons/src/config/EnvironmentVariablesService.ts @@ -0,0 +1,67 @@ +import { ConfigService } from '.'; + +/** + * Class EnvironmentVariablesService + * + * This class is used to return environment variables that are available in the runtime of + * the current Lambda invocation. + * These variables can be a mix of runtime environment variables set by AWS and + * variables that can be set by the developer additionally. + * + * @class + * @extends {ConfigService} + * @see https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime + * @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables + */ +class EnvironmentVariablesService extends ConfigService { + + /** + * @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables + * @protected + */ + protected serviceNameVariable = 'POWERTOOLS_SERVICE_NAME'; + // Reserved environment variables + private xRayTraceIdVariable = '_X_AMZN_TRACE_ID'; + + /** + * It returns the value of an environment variable that has given name. + * + * @param {string} name + * @returns {string} + */ + public get(name: string): string { + return process.env[name]?.trim() || ''; + } + + /** + * It returns the value of the POWERTOOLS_SERVICE_NAME environment variable. + * + * @returns {string} + */ + public getServiceName(): string { + return this.get(this.serviceNameVariable); + } + + /** + * It returns the value of the _X_AMZN_TRACE_ID environment variable. + * + * The AWS X-Ray Trace data available in the environment variable has this format: + * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`, + * + * The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`. + * + * @returns {string} + */ + public getXrayTraceId(): string | undefined { + const xRayTraceId = this.get(this.xRayTraceIdVariable); + + if (xRayTraceId === '') return undefined; + + return xRayTraceId.split(';')[0].replace('Root=', ''); + } + +} + +export { + EnvironmentVariablesService, +}; \ No newline at end of file diff --git a/packages/commons/src/config/index.ts b/packages/commons/src/config/index.ts new file mode 100644 index 0000000000..86697bdab3 --- /dev/null +++ b/packages/commons/src/config/index.ts @@ -0,0 +1,2 @@ +export * from './ConfigService'; +export * from './EnvironmentVariablesService'; \ No newline at end of file diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts index 4b333f1d09..f921ac63a6 100644 --- a/packages/commons/src/index.ts +++ b/packages/commons/src/index.ts @@ -1,4 +1,5 @@ export * from './utils/lambda'; export * from './Utility'; +export * from './config'; export * as ContextExamples from './samples/resources/contexts'; export * as Events from './samples/resources/events'; \ No newline at end of file diff --git a/packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts b/packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts new file mode 100644 index 0000000000..692a5b1ff0 --- /dev/null +++ b/packages/commons/tests/unit/config/EnvironmentVariablesService.test.ts @@ -0,0 +1,113 @@ +/** + * Test EnvironmentVariablesService class + * + * @group unit/commons/all + */ + +import { EnvironmentVariablesService } from '../../../src/config'; + +describe('Class: EnvironmentVariablesService', () => { + + const ENVIRONMENT_VARIABLES = process.env; + + beforeEach(() => { + jest.resetModules(); + process.env = { ...ENVIRONMENT_VARIABLES }; + }); + + afterAll(() => { + process.env = ENVIRONMENT_VARIABLES; + }); + + describe('Method: get', () => { + + test('When the variable IS present, it returns the value of a runtime variable', () => { + + // Prepare + process.env.CUSTOM_VARIABLE = 'my custom value'; + const service = new EnvironmentVariablesService(); + + // Act + const value = service.get('CUSTOM_VARIABLE'); + + // Assess + expect(value).toEqual('my custom value'); + + }); + + test('When the variable IS NOT present, it returns an empty string', () => { + + // Prepare + delete process.env.CUSTOM_VARIABLE; + const service = new EnvironmentVariablesService(); + + // Act + const value = service.get('CUSTOM_VARIABLE'); + + // Assess + expect(value).toEqual(''); + + }); + + }); + + describe('Method: getServiceName', () => { + + test('It returns the value of the environment variable POWERTOOLS_SERVICE_NAME', () => { + + // Prepare + process.env.POWERTOOLS_SERVICE_NAME = 'shopping-cart-api'; + const service = new EnvironmentVariablesService(); + + // Act + const value = service.getServiceName(); + + // Assess + expect(value).toEqual('shopping-cart-api'); + }); + + }); + + describe('Method: getXrayTraceId', () => { + + test('It returns the value of the environment variable _X_AMZN_TRACE_ID', () => { + + // Prepare + process.env._X_AMZN_TRACE_ID = 'abcd123456789'; + const service = new EnvironmentVariablesService(); + + // Act + const value = service.getXrayTraceId(); + + // Assess + expect(value).toEqual('abcd123456789'); + }); + test('It returns the value of the Root X-Ray segment ID properly formatted', () => { + + // Prepare + process.env._X_AMZN_TRACE_ID = 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1'; + const service = new EnvironmentVariablesService(); + + // Act + const value = service.getXrayTraceId(); + + // Assess + expect(value).toEqual('1-5759e988-bd862e3fe1be46a994272793'); + }); + + test('It returns the value of the Root X-Ray segment ID properly formatted', () => { + + // Prepare + delete process.env._X_AMZN_TRACE_ID; + const service = new EnvironmentVariablesService(); + + // Act + const value = service.getXrayTraceId(); + + // Assess + expect(value).toEqual(undefined); + }); + + }); + +}); \ No newline at end of file diff --git a/packages/logger/CHANGELOG.md b/packages/logger/CHANGELOG.md index 469426f99b..5781749f06 100644 --- a/packages/logger/CHANGELOG.md +++ b/packages/logger/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + + +### Features + +* **all:** moved EnvService to commons + exposed getXrayTraceId in tracer ([#1123](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1123)) ([c8e3c15](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/c8e3c15b64142ebe6f43835a5917ecba26293a32)) + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/packages/logger/package.json b/packages/logger/package.json index cea2f8c60b..08ce5ebf59 100644 --- a/packages/logger/package.json +++ b/packages/logger/package.json @@ -1,6 +1,6 @@ { "name": "@aws-lambda-powertools/logger", - "version": "1.3.0", + "version": "1.4.0", "description": "The logging package for the AWS Lambda Powertools for TypeScript library", "author": { "name": "Amazon Web Services", @@ -50,7 +50,7 @@ "url": "https://github.com/awslabs/aws-lambda-powertools-typescript/issues" }, "dependencies": { - "@aws-lambda-powertools/commons": "^1.3.0", + "@aws-lambda-powertools/commons": "^1.4.0", "lodash.clonedeep": "^4.5.0", "lodash.merge": "^4.6.2", "lodash.pickby": "^4.6.0" diff --git a/packages/logger/src/Logger.ts b/packages/logger/src/Logger.ts index 805e7a5d1a..be9ee86253 100644 --- a/packages/logger/src/Logger.ts +++ b/packages/logger/src/Logger.ts @@ -117,7 +117,8 @@ class Logger extends Utility implements ClassThatLogs { private static readonly defaultServiceName: string = 'service_undefined'; - private envVarsService?: EnvironmentVariablesService; + // envVarsService is always initialized in the constructor in setOptions() + private envVarsService!: EnvironmentVariablesService; private logEvent: boolean = false; @@ -455,7 +456,7 @@ class Logger extends Utility implements ClassThatLogs { logLevel, timestamp: new Date(), message: typeof input === 'string' ? input : input.message, - xRayTraceId: this.getXrayTraceId(), + xRayTraceId: this.envVarsService.getXrayTraceId(), }, this.getPowertoolLogData()); const logItem = new LogItem({ @@ -545,23 +546,6 @@ class Logger extends Utility implements ClassThatLogs { return <number> this.powertoolLogData.sampleRateValue; } - /** - * It returns the current X-Ray Trace ID parsing the content of the `_X_AMZN_TRACE_ID` env variable. - * - * The X-Ray Trace data available in the environment variable has this format: - * `Root=1-5759e988-bd862e3fe1be46a994272793;Parent=557abcec3ee5a047;Sampled=1`, - * - * The actual Trace ID is: `1-5759e988-bd862e3fe1be46a994272793`. - * - * @private - * @returns {string} - */ - private getXrayTraceId(): string { - const xRayTraceId = this.getEnvVarsService().getXrayTraceId(); - - return xRayTraceId.length > 0 ? xRayTraceId.split(';')[0].replace('Root=', '') : xRayTraceId; - } - /** * It returns true if the provided log level is valid. * diff --git a/packages/logger/src/config/ConfigService.ts b/packages/logger/src/config/ConfigService.ts deleted file mode 100644 index 6479ab32ee..0000000000 --- a/packages/logger/src/config/ConfigService.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { ConfigServiceInterface } from '.'; - -/** - * Abstract class ConfigService - * - * This class defines common methods and variables that can be set by the developer - * in the runtime. - * - * @class - * @abstract - * @implements {ConfigServiceInterface} - * @see https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime - * @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables - */ -abstract class ConfigService implements ConfigServiceInterface { - - /** - * @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables - * @protected - */ - protected currentEnvironmentVariable = 'ENVIRONMENT'; - protected logEventVariable = 'POWERTOOLS_LOGGER_LOG_EVENT'; - protected logLevelVariable = 'LOG_LEVEL'; - protected sampleRateValueVariable = 'POWERTOOLS_LOGGER_SAMPLE_RATE'; - protected serviceNameVariable = 'POWERTOOLS_SERVICE_NAME'; - - /** - * It returns the value of an environment variable that has given name. - * - * @param {string} name - * @returns {string} - */ - public abstract get(name: string): string; - - /** - * It returns the value of the ENVIRONMENT environment variable. - * - * @returns {string} - */ - public abstract getCurrentEnvironment(): string; - - /** - * It returns the value of the POWERTOOLS_LOGGER_LOG_EVENT environment variable. - * - * @returns {boolean} - */ - public abstract getLogEvent(): boolean; - - /** - * It returns the value of the LOG_LEVEL environment variable. - * - * @returns {string} - */ - public abstract getLogLevel(): string; - - /** - * It returns the value of the POWERTOOLS_LOGGER_SAMPLE_RATE environment variable. - * - * @returns {string|undefined} - */ - public abstract getSampleRateValue(): number | undefined; - - /** - * It returns the value of the POWERTOOLS_SERVICE_NAME environment variable. - * - * @returns {string} - */ - public abstract getServiceName(): string; - - /** - * It returns true if the string value represents a boolean true value. - * - * @param {string} value - * @returns boolean - * @protected - */ - protected isValueTrue(value: string): boolean { - return value.toLowerCase() === 'true' || value === '1'; - } - -} - -export { - ConfigService, -}; \ No newline at end of file diff --git a/packages/logger/src/config/EnvironmentVariablesService.ts b/packages/logger/src/config/EnvironmentVariablesService.ts index 2484252a65..28b5ee7b4b 100644 --- a/packages/logger/src/config/EnvironmentVariablesService.ts +++ b/packages/logger/src/config/EnvironmentVariablesService.ts @@ -1,4 +1,5 @@ -import { ConfigService } from '.'; +import { ConfigServiceInterface } from './ConfigServiceInterface'; +import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons'; /** * Class EnvironmentVariablesService @@ -9,28 +10,22 @@ import { ConfigService } from '.'; * variables that can be set by the developer additionally. * * @class - * @extends {ConfigService} + * @extends {CommonEnvironmentVariablesService} + * @implements {ConfigServiceInterface} * @see https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime * @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/#environment-variables */ -class EnvironmentVariablesService extends ConfigService { +class EnvironmentVariablesService extends CommonEnvironmentVariablesService implements ConfigServiceInterface { // Reserved environment variables private awsRegionVariable = 'AWS_REGION'; + private currentEnvironmentVariable = 'ENVIRONMENT'; private functionNameVariable = 'AWS_LAMBDA_FUNCTION_NAME'; private functionVersionVariable = 'AWS_LAMBDA_FUNCTION_VERSION'; + private logEventVariable = 'POWERTOOLS_LOGGER_LOG_EVENT'; + private logLevelVariable = 'LOG_LEVEL'; private memoryLimitInMBVariable = 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE'; - private xRayTraceIdVariable = '_X_AMZN_TRACE_ID'; - - /** - * It returns the value of an environment variable that has given name. - * - * @param {string} name - * @returns {string} - */ - public get(name: string): string { - return process.env[name]?.trim() || ''; - } + private sampleRateValueVariable = 'POWERTOOLS_LOGGER_SAMPLE_RATE'; /** * It returns the value of the AWS_REGION environment variable. @@ -85,7 +80,9 @@ class EnvironmentVariablesService extends ConfigService { * @returns {boolean} */ public getLogEvent(): boolean { - return this.isValueTrue(this.get(this.logEventVariable)); + const value = this.get(this.logEventVariable); + + return value.toLowerCase() === 'true' || value === '1'; } /** @@ -108,24 +105,6 @@ class EnvironmentVariablesService extends ConfigService { return (value && value.length > 0) ? Number(value) : undefined; } - /** - * It returns the value of the POWERTOOLS_SERVICE_NAME environment variable. - * - * @returns {string} - */ - public getServiceName(): string { - return this.get(this.serviceNameVariable); - } - - /** - * It returns the value of the _X_AMZN_TRACE_ID environment variable. - * - * @returns {string} - */ - public getXrayTraceId(): string { - return this.get(this.xRayTraceIdVariable); - } - } export { diff --git a/packages/logger/src/config/index.ts b/packages/logger/src/config/index.ts index b8a77f2ab4..0f036d810e 100644 --- a/packages/logger/src/config/index.ts +++ b/packages/logger/src/config/index.ts @@ -1,3 +1,2 @@ -export * from './ConfigService'; export * from './ConfigServiceInterface'; export * from './EnvironmentVariablesService'; \ No newline at end of file diff --git a/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts b/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts index 18d1e29221..b64c4c228f 100644 --- a/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts +++ b/packages/logger/tests/unit/config/EnvironmentVariablesService.test.ts @@ -19,38 +19,6 @@ describe('Class: EnvironmentVariablesService', () => { process.env = ENVIRONMENT_VARIABLES; }); - describe('Method: get', () => { - - test('When the variable IS present, it returns the value of a runtime variable', () => { - - // Prepare - process.env.CUSTOM_VARIABLE = 'my custom value'; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.get('CUSTOM_VARIABLE'); - - // Assess - expect(value).toEqual('my custom value'); - - }); - - test('When the variable IS NOT present, it returns an empty string', () => { - - // Prepare - delete process.env.CUSTOM_VARIABLE; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.get('CUSTOM_VARIABLE'); - - // Assess - expect(value).toEqual(''); - - }); - - }); - describe('Method: getAwsRegion', () => { test('It returns the value of the environment variable AWS_REGION', () => { @@ -252,38 +220,4 @@ describe('Class: EnvironmentVariablesService', () => { }); - describe('Method: getServiceName', () => { - - test('It returns the value of the environment variable POWERTOOLS_SERVICE_NAME', () => { - - // Prepare - process.env.POWERTOOLS_SERVICE_NAME = 'shopping-cart-api'; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.getServiceName(); - - // Assess - expect(value).toEqual('shopping-cart-api'); - }); - - }); - - describe('Method: getXrayTraceId', () => { - - test('It returns the value of the environment variable _X_AMZN_TRACE_ID', () => { - - // Prepare - process.env._X_AMZN_TRACE_ID = 'abcd123456789'; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.getXrayTraceId(); - - // Assess - expect(value).toEqual('abcd123456789'); - }); - - }); - }); \ No newline at end of file diff --git a/packages/metrics/CHANGELOG.md b/packages/metrics/CHANGELOG.md index dae17bc14e..fa2ecba6cb 100644 --- a/packages/metrics/CHANGELOG.md +++ b/packages/metrics/CHANGELOG.md @@ -3,6 +3,22 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + + +### Bug Fixes + +* **metrics:** metadata and dimensions not cleared on publish ([#1129](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1129)) ([b209c30](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/b209c30df92da07875f204f7f211294feea729db)) + + +### Features + +* **all:** moved EnvService to commons + exposed getXrayTraceId in tracer ([#1123](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1123)) ([c8e3c15](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/c8e3c15b64142ebe6f43835a5917ecba26293a32)) + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/packages/metrics/package.json b/packages/metrics/package.json index b4f81b3a1e..6f789f46fa 100644 --- a/packages/metrics/package.json +++ b/packages/metrics/package.json @@ -1,6 +1,6 @@ { "name": "@aws-lambda-powertools/metrics", - "version": "1.3.0", + "version": "1.4.0", "description": "The metrics package for the AWS Lambda Powertools for TypeScript library", "author": { "name": "Amazon Web Services", @@ -49,7 +49,7 @@ "url": "https://github.com/awslabs/aws-lambda-powertools-typescript/issues" }, "dependencies": { - "@aws-lambda-powertools/commons": "^1.3.0" + "@aws-lambda-powertools/commons": "^1.4.0" }, "keywords": [ "aws", diff --git a/packages/metrics/src/Metrics.ts b/packages/metrics/src/Metrics.ts index 429e8a7d54..48ba88cd78 100644 --- a/packages/metrics/src/Metrics.ts +++ b/packages/metrics/src/Metrics.ts @@ -287,7 +287,9 @@ class Metrics extends Utility implements MetricsInterface { public publishStoredMetrics(): void { const target = this.serializeMetrics(); console.log(JSON.stringify(target)); - this.storedMetrics = {}; + this.clearMetrics(); + this.clearDimensions(); + this.clearMetadata(); } /** @@ -450,8 +452,8 @@ class Metrics extends Utility implements MetricsInterface { private setService(service: string | undefined): void { const targetService = (service || - this.getCustomConfigService()?.getService() || - this.getEnvVarsService().getService()) as string; + this.getCustomConfigService()?.getServiceName() || + this.getEnvVarsService().getServiceName()) as string; if (targetService.length > 0) { this.addDimension('service', targetService); } diff --git a/packages/metrics/src/config/ConfigService.ts b/packages/metrics/src/config/ConfigService.ts deleted file mode 100644 index a1fef20267..0000000000 --- a/packages/metrics/src/config/ConfigService.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { ConfigServiceInterface } from '.'; - -abstract class ConfigService implements ConfigServiceInterface { - - public abstract get(name: string): string; - public abstract getNamespace(): string; - public abstract getService(): string; - -} - -export { - ConfigService, -}; \ No newline at end of file diff --git a/packages/metrics/src/config/ConfigServiceInterface.ts b/packages/metrics/src/config/ConfigServiceInterface.ts index 65406c5037..0c009b3e79 100644 --- a/packages/metrics/src/config/ConfigServiceInterface.ts +++ b/packages/metrics/src/config/ConfigServiceInterface.ts @@ -2,7 +2,7 @@ interface ConfigServiceInterface { get?(name: string): string getNamespace(): string - getService(): string + getServiceName(): string } diff --git a/packages/metrics/src/config/EnvironmentVariablesService.ts b/packages/metrics/src/config/EnvironmentVariablesService.ts index b45c51ecc1..5bb4eb712b 100644 --- a/packages/metrics/src/config/EnvironmentVariablesService.ts +++ b/packages/metrics/src/config/EnvironmentVariablesService.ts @@ -1,20 +1,13 @@ -import { ConfigService } from '.'; +import { ConfigServiceInterface } from './ConfigServiceInterface'; +import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons'; -class EnvironmentVariablesService extends ConfigService { +class EnvironmentVariablesService extends CommonEnvironmentVariablesService implements ConfigServiceInterface { private namespaceVariable = 'POWERTOOLS_METRICS_NAMESPACE'; - private serviceVariable = 'POWERTOOLS_SERVICE_NAME'; - - public get(name: string): string { - return process.env[name]?.trim() || ''; - } public getNamespace(): string { return this.get(this.namespaceVariable); } - public getService(): string { - return this.get(this.serviceVariable); - } } diff --git a/packages/metrics/src/config/index.ts b/packages/metrics/src/config/index.ts index b8a77f2ab4..0f036d810e 100644 --- a/packages/metrics/src/config/index.ts +++ b/packages/metrics/src/config/index.ts @@ -1,3 +1,2 @@ -export * from './ConfigService'; export * from './ConfigServiceInterface'; export * from './EnvironmentVariablesService'; \ No newline at end of file diff --git a/packages/metrics/tests/unit/Metrics.test.ts b/packages/metrics/tests/unit/Metrics.test.ts index 8ce2956969..b3f0086d70 100644 --- a/packages/metrics/tests/unit/Metrics.test.ts +++ b/packages/metrics/tests/unit/Metrics.test.ts @@ -80,6 +80,35 @@ describe('Class: Metrics', () => { expect(loggedData[additionalDimension.name]).toEqual(additionalDimension.value); }); + test('Publish Stored Metrics should clear added dimensions', async () => { + const metrics = new Metrics({ namespace: 'test' }); + const dimensionItem = { name: 'dimensionName', value: 'dimensionValue' }; + + class LambdaFunction implements LambdaInterface { + @metrics.logMetrics() + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + public handler<TEvent, TResult>( + _event: TEvent, + _context: Context, + _callback: Callback<TResult>, + ): void | Promise<TResult> { + metrics.addMetric('test_name_1', MetricUnits.Count, 1); + metrics.addDimension(dimensionItem.name, dimensionItem.value); + metrics.publishStoredMetrics(); + } + } + + await new LambdaFunction().handler(dummyEvent, dummyContext.helloworldContext, () => console.log('Lambda invoked!')); + const loggedData = [ JSON.parse(consoleSpy.mock.calls[0][0]), JSON.parse(consoleSpy.mock.calls[1][0]) ]; + + expect(console.log).toBeCalledTimes(2); + expect(loggedData[0][dimensionItem.name]).toEqual(dimensionItem.value); + expect(loggedData[0]._aws.CloudWatchMetrics[0].Dimensions[0].length).toEqual(1); + expect(loggedData[1][dimensionItem.name]).toBeUndefined(); + expect(loggedData[1]._aws.CloudWatchMetrics[0].Dimensions[0].length).toEqual(0); + }); + test('Adding more than max dimensions should throw error', () => { expect.assertions(1); const metrics = new Metrics(); @@ -144,6 +173,33 @@ describe('Class: Metrics', () => { expect(loggedData[metadataItem.name]).toEqual(metadataItem.value); expect(postClearLoggedData[metadataItem.name]).toBeUndefined(); }); + + test('Publish Stored Metrics should clear metadata', async () => { + const metrics = new Metrics({ namespace: 'test' }); + const metadataItem = { name: 'metaName', value: 'metaValue' }; + + class LambdaFunction implements LambdaInterface { + @metrics.logMetrics() + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + public handler<TEvent, TResult>( + _event: TEvent, + _context: Context, + _callback: Callback<TResult>, + ): void | Promise<TResult> { + metrics.addMetric('test_name_1', MetricUnits.Count, 1); + metrics.addMetadata(metadataItem.name, metadataItem.value); + metrics.publishStoredMetrics(); + } + } + + await new LambdaFunction().handler(dummyEvent, dummyContext.helloworldContext, () => console.log('Lambda invoked!')); + const loggedData = [ JSON.parse(consoleSpy.mock.calls[0][0]), JSON.parse(consoleSpy.mock.calls[1][0]) ]; + + expect(console.log).toBeCalledTimes(2); + expect(loggedData[0][metadataItem.name]).toEqual(metadataItem.value); + expect(loggedData[1][metadataItem.name]).toBeUndefined(); + }); }); describe('Feature: Default Dimensions', () => { @@ -684,7 +740,7 @@ describe('Class: Metrics', () => { const serviceName = 'Custom Provider Service Name'; const namespace = 'Custom Provider namespace'; const customConfigService = { - getService: () => serviceName, + getServiceName: () => serviceName, getNamespace: () => namespace, }; diff --git a/packages/tracer/CHANGELOG.md b/packages/tracer/CHANGELOG.md index 3e3f65710f..7b6a68e751 100644 --- a/packages/tracer/CHANGELOG.md +++ b/packages/tracer/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [1.4.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.3.0...v1.4.0) (2022-10-27) + + +### Features + +* **all:** moved EnvService to commons + exposed getXrayTraceId in tracer ([#1123](https://github.com/awslabs/aws-lambda-powertools-typescript/issues/1123)) ([c8e3c15](https://github.com/awslabs/aws-lambda-powertools-typescript/commit/c8e3c15b64142ebe6f43835a5917ecba26293a32)) + + + + + # [1.3.0](https://github.com/awslabs/aws-lambda-powertools-typescript/compare/v1.2.1...v1.3.0) (2022-10-17) diff --git a/packages/tracer/package.json b/packages/tracer/package.json index b4c974a48f..f08bcb0a36 100644 --- a/packages/tracer/package.json +++ b/packages/tracer/package.json @@ -1,6 +1,6 @@ { "name": "@aws-lambda-powertools/tracer", - "version": "1.3.0", + "version": "1.4.0", "description": "The tracer package for the AWS Lambda Powertools for TypeScript library", "author": { "name": "Amazon Web Services", @@ -50,7 +50,7 @@ "url": "https://github.com/awslabs/aws-lambda-powertools-typescript/issues" }, "dependencies": { - "@aws-lambda-powertools/commons": "^1.3.0", + "@aws-lambda-powertools/commons": "^1.4.0", "aws-xray-sdk-core": "^3.3.6" }, "keywords": [ diff --git a/packages/tracer/src/Tracer.ts b/packages/tracer/src/Tracer.ts index e4fe06553b..09ac5e3314 100644 --- a/packages/tracer/src/Tracer.ts +++ b/packages/tracer/src/Tracer.ts @@ -462,6 +462,44 @@ class Tracer extends Utility implements TracerInterface { return descriptor; }; } + + /** + * Get the current root AWS X-Ray trace id. + * + * Utility method that returns the current AWS X-Ray Root trace id. Useful as correlation id for downstream processes. + * + * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces + * + * @example + * ```typescript + * import { Tracer } from '@aws-lambda-powertools/tracer'; + * + * const tracer = new Tracer({ serviceName: 'serverlessAirline' }); + * + * export const handler = async () => { + * + * try { + * ... + * } catch (err) { + * const rootTraceId = tracer.getRootXrayTraceId(); + * + * // Example of returning an error response + * return { + * statusCode: 500, + * // Include the rootTraceId in the response so we can show a "contact support" button that + * // takes the customer to a customer service form with the trace as additional context. + * body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`, + * headers: { "_X_AMZN_TRACE_ID": rootTraceId }, + * }; + * } + * } + * ``` + * + * @returns string - The root X-Ray trace id. + */ + public getRootXrayTraceId(): string | undefined { + return this.envVarsService.getXrayTraceId(); + } /** * Get the active segment or subsegment in the current scope. diff --git a/packages/tracer/src/TracerInterface.ts b/packages/tracer/src/TracerInterface.ts index 20ae8f60c9..128a2c5553 100644 --- a/packages/tracer/src/TracerInterface.ts +++ b/packages/tracer/src/TracerInterface.ts @@ -12,6 +12,7 @@ interface TracerInterface { captureLambdaHandler(options?: CaptureLambdaHandlerOptions): HandlerMethodDecorator captureMethod(options?: CaptureMethodOptions): MethodDecorator getSegment(): Segment | Subsegment + getRootXrayTraceId(): string | undefined isTracingEnabled(): boolean putAnnotation: (key: string, value: string | number | boolean) => void putMetadata: (key: string, value: unknown, namespace?: string | undefined) => void diff --git a/packages/tracer/src/config/ConfigService.ts b/packages/tracer/src/config/ConfigService.ts deleted file mode 100644 index bbaffdb7ed..0000000000 --- a/packages/tracer/src/config/ConfigService.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { ConfigServiceInterface } from '.'; - -abstract class ConfigService implements ConfigServiceInterface { - - // Custom environment variables - protected serviceNameVariable = 'POWERTOOLS_SERVICE_NAME'; - protected tracerCaptureErrorVariable = 'POWERTOOLS_TRACER_CAPTURE_ERROR'; - protected tracerCaptureHTTPsRequestsVariable = 'POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS'; - protected tracerCaptureResponseVariable = 'POWERTOOLS_TRACER_CAPTURE_RESPONSE'; - protected tracingEnabledVariable = 'POWERTOOLS_TRACE_ENABLED'; - - public abstract get(name: string): string; - - public abstract getCaptureHTTPsRequests(): string; - - public abstract getServiceName(): string; - - public abstract getTracingCaptureError(): string; - - public abstract getTracingCaptureResponse(): string; - - public abstract getTracingEnabled(): string; - -} - -export { - ConfigService -}; \ No newline at end of file diff --git a/packages/tracer/src/config/EnvironmentVariablesService.ts b/packages/tracer/src/config/EnvironmentVariablesService.ts index 7fb780e2f8..d8503864c1 100644 --- a/packages/tracer/src/config/EnvironmentVariablesService.ts +++ b/packages/tracer/src/config/EnvironmentVariablesService.ts @@ -1,15 +1,15 @@ -import { ConfigService } from '.'; +import { ConfigServiceInterface } from './ConfigServiceInterface'; +import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons'; -class EnvironmentVariablesService extends ConfigService { +class EnvironmentVariablesService extends CommonEnvironmentVariablesService implements ConfigServiceInterface { // Environment variables private awsExecutionEnv = 'AWS_EXECUTION_ENV'; private samLocalVariable = 'AWS_SAM_LOCAL'; - private xRayTraceIdVariable = '_X_AMZN_TRACE_ID'; - - public get(name: string): string { - return process.env[name]?.trim() || ''; - } + private tracerCaptureErrorVariable = 'POWERTOOLS_TRACER_CAPTURE_ERROR'; + private tracerCaptureHTTPsRequestsVariable = 'POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS'; + private tracerCaptureResponseVariable = 'POWERTOOLS_TRACER_CAPTURE_RESPONSE'; + private tracingEnabledVariable = 'POWERTOOLS_TRACE_ENABLED'; public getAwsExecutionEnv(): string { return this.get(this.awsExecutionEnv); @@ -23,10 +23,6 @@ class EnvironmentVariablesService extends ConfigService { return this.get(this.samLocalVariable); } - public getServiceName(): string { - return this.get(this.serviceNameVariable); - } - public getTracingCaptureError(): string { return this.get(this.tracerCaptureErrorVariable); } @@ -39,9 +35,6 @@ class EnvironmentVariablesService extends ConfigService { return this.get(this.tracingEnabledVariable); } - public getXrayTraceId(): string { - return this.get(this.xRayTraceIdVariable); - } } export { diff --git a/packages/tracer/src/config/index.ts b/packages/tracer/src/config/index.ts index b8a77f2ab4..0f036d810e 100644 --- a/packages/tracer/src/config/index.ts +++ b/packages/tracer/src/config/index.ts @@ -1,3 +1,2 @@ -export * from './ConfigService'; export * from './ConfigServiceInterface'; export * from './EnvironmentVariablesService'; \ No newline at end of file diff --git a/packages/tracer/tests/unit/Tracer.test.ts b/packages/tracer/tests/unit/Tracer.test.ts index ce1acc976e..f541f2e4db 100644 --- a/packages/tracer/tests/unit/Tracer.test.ts +++ b/packages/tracer/tests/unit/Tracer.test.ts @@ -271,6 +271,23 @@ describe('Class: Tracer', () => { }); + describe('Method: getRootXrayTraceId', () => { + + test('when called, it returns the X-Ray trace ID', () => { + + // Prepare + const tracer: Tracer = new Tracer(); + + // Act + const xRayTraceId = tracer.getRootXrayTraceId(); + + // Assess + expect(xRayTraceId).toBe('1-abcdef12-3456abcdef123456abcdef12'); + + }); + + }); + describe('Method: getSegment', () => { test('when called outside of a namespace or without parent segment, and tracing is enabled, it throws an error', () => { diff --git a/packages/tracer/tests/unit/config/EnvironmentVariablesService.test.ts b/packages/tracer/tests/unit/config/EnvironmentVariablesService.test.ts index 30e0db93f2..478944ce31 100644 --- a/packages/tracer/tests/unit/config/EnvironmentVariablesService.test.ts +++ b/packages/tracer/tests/unit/config/EnvironmentVariablesService.test.ts @@ -19,38 +19,6 @@ describe('Class: EnvironmentVariablesService', () => { process.env = ENVIRONMENT_VARIABLES; }); - describe('Method: get', () => { - - test('When the variable IS present, it returns the value of a runtime variable', () => { - - // Prepare - process.env.CUSTOM_VARIABLE = 'my custom value'; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.get('CUSTOM_VARIABLE'); - - // Assess - expect(value).toEqual('my custom value'); - - }); - - test('When the variable IS NOT present, it returns an empty string', () => { - - // Prepare - delete process.env.CUSTOM_VARIABLE; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.get('CUSTOM_VARIABLE'); - - // Assess - expect(value).toEqual(''); - - }); - - }); - describe('Method: getTracingEnabled', () => { test('It returns the value of the environment variable POWERTOOLS_TRACE_ENABLED', () => { @@ -119,40 +87,6 @@ describe('Class: EnvironmentVariablesService', () => { }); - describe('Method: getServiceName', () => { - - test('It returns the value of the environment variable POWERTOOLS_SERVICE_NAME', () => { - - // Prepare - process.env.POWERTOOLS_SERVICE_NAME = 'shopping-cart-api'; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.getServiceName(); - - // Assess - expect(value).toEqual('shopping-cart-api'); - }); - - }); - - describe('Method: getXrayTraceId', () => { - - test('It returns the value of the environment variable _X_AMZN_TRACE_ID', () => { - - // Prepare - process.env._X_AMZN_TRACE_ID = 'abcd123456789'; - const service = new EnvironmentVariablesService(); - - // Act - const value = service.getXrayTraceId(); - - // Assess - expect(value).toEqual('abcd123456789'); - }); - - }); - describe('Method: getSamLocal', () => { test('It returns the value of the environment variable AWS_SAM_LOCAL', () => {