### Setup and Branching Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/CONTRIBUTING.md Clone the repository, create a new branch for your changes, and install project dependencies. ```bash git clone git@github.com:/serverless-plugin-datadog.git git checkout -b yarn install ``` -------------------------------- ### Serverless.yml Configuration Example Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/02-api-reference-main.md Example serverless.yml configuration demonstrating how to register the serverless-plugin-datadog and set custom Datadog provider options. ```yaml plugins: - serverless-plugin-datadog provider: name: aws runtime: nodejs20.x region: us-east-1 custom: datadog: site: datadoghq.com apiKey: ${env:DATADOG_API_KEY} addLayers: true addExtension: true enableDDTracing: true enableDDLogs: true functions: myFunction: handler: src/index.handler runtime: nodejs20.x ``` -------------------------------- ### Console Output Example for printOutputs Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md An example of the formatted console output from the printOutputs function, including Datadog monitoring links. ```text Datadog Monitoring functions myFunction: https://app.datadoghq.com/functions?... View Serverless Monitors https://app.datadoghq.com/monitors/manage?q=tag:(... ``` -------------------------------- ### Example: Use SimpleGit Instance Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Demonstrates how to use the SimpleGit instance to check if the current directory is a git repository and retrieve the latest commit hash. ```typescript const git = await newSimpleGit(); if (git && await git.checkIsRepo()) { const commit = await git.log(['-1', '--format=%H']); console.log(commit); } ``` -------------------------------- ### LayerJSON Structure Example Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/05-api-reference-layer.md Example structure for `layers.json` and `layers-gov.json` files. Maps regions and runtimes to Datadog Lambda layer ARNs. ```json { "regions": { "us-east-1": { "nodejs20.x": "arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Node20-x:20", "python3.11": "arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Python311:30", "extension": "arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Extension:42" } } } ``` -------------------------------- ### RecommendedMonitors Type Example Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md An example of a RecommendedMonitors type, which is a map of serverless monitor IDs to their definitions. This is used to store and reference predefined monitor configurations. ```typescript { "high_error_rate": { ... }, "timeout": { ... }, "out_of_memory": { ... } } ``` -------------------------------- ### Monitor Type Example Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md An example of a monitor configuration object, where the key is a serverless monitor ID and the value is a MonitorParams object. This structure is used for defining monitors within the plugin configuration. ```typescript { "high_error_rate": { threshold: 0.1, options: { thresholds: { critical: 0.1 } } } } ``` -------------------------------- ### Example CloudFormation Output for Datadog Links Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md An example of the JSON structure generated for CloudFormation outputs, providing links to Datadog function pages. ```json { "DatadogMonitorMyFunction": { "Description": "See myFunction in Datadog", "Value": "https://app.datadoghq.com/functions?cloud=aws&entity_view=lambda_functions&selection=aws-lambda-functions%2Bmyfunction%2Bus-east-1%2B123456789012" } } ``` -------------------------------- ### Serverless Plugin Datadog Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/01-overview.md Example configuration for the Datadog plugin within the serverless.yml file. Set site, API key, and enable features like layers and tracing. ```yaml custom: datadog: site: datadoghq.com apiKey: xxx addLayers: true addExtension: true enableDDTracing: true ``` -------------------------------- ### Configure Datadog Monitors via YAML Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md This YAML configuration demonstrates how to define and customize Datadog monitors within your serverless application. It shows examples for predefined monitors like 'high_error_rate' and 'timeout', as well as a fully custom metric alert. ```yaml custom: datadog: monitors: - high_error_rate: threshold: 0.15 - timeout: {} - custom_monitor: type: "metric alert" name: "Custom Lambda Monitor" query: "avg:custom.metric{env:prod} > 100" message: "Custom alert: {{function_name}}" ``` -------------------------------- ### Example Node.js Function Environment Variables Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/10-environment-variables.md This JSON object displays the environment variables automatically managed by the Datadog Serverless Plugin for a Node.js function. Users should not set these directly in serverless.yml. ```json { "DD_API_KEY": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx", "DD_SITE": "datadoghq.com", "DD_SERVICE": "my-service", "DD_ENV": "production", "DD_TRACE_ENABLED": "true", "DD_MERGE_XRAY_TRACES": "false", "DD_LOGS_INJECTION": "false", "DD_SERVERLESS_LOGS_ENABLED": "true", "DD_CAPTURE_LAMBDA_PAYLOAD": "false", "DD_LAMBDA_HANDLER": "src/index.handler", "DD_COLD_START_TRACING": "true", "DD_MIN_COLD_START_DURATION": "3", "DD_TAGS": "git.commit.sha:abc123,git.repository_url:https://github.com/org/repo" } ``` -------------------------------- ### Default Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/04-api-reference-env.md Provides the default configuration values that are applied when specific options are not provided by the user. This ensures a baseline setup. ```typescript export const defaultConfiguration: Configuration = { ... } ``` -------------------------------- ### Get Plugin Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/03-configuration.md This function reads the plugin configuration from the Serverless service object, merging defaults with user-specified values. ```typescript export function getConfig(service: Service): Configuration ``` -------------------------------- ### Get Datadog Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/04-api-reference-env.md Extracts and merges Datadog configuration from the Serverless service object with default values. Use this to access the plugin's configuration settings. ```typescript export function getConfig(service: Service): Configuration ``` ```typescript import { getConfig } from './env'; import Service from 'serverless/classes/Service'; const config = getConfig(service); console.log(config.site); // "datadoghq.com" console.log(config.addExtension); // true (default) ``` -------------------------------- ### Get Default FIPS Enabled Flag Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/05-api-reference-layer.md Determines if FIPS-compliant extensions should be used based on plugin configuration and AWS region. Returns true if the region starts with 'us-gov-' and FIPS is enabled in the configuration. ```typescript export function getDefaultIsFIPSEnabledFlag( config: Configuration, region: string ): boolean ``` ```typescript getDefaultIsFIPSEnabledFlag(config, "us-gov-west-1"); // true getDefaultIsFIPSEnabledFlag(config, "us-east-1"); // false ``` -------------------------------- ### Local Development and Testing Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/CONTRIBUTING.md Build the project, link it locally for development, and deploy to a testing application to verify changes. ```bash # From the root of the serverless-plugin-datadog repo yarn build cd dist yarn link # From the root of your own serverless application yarn link "serverless-plugin-datadog" sls deploy ``` -------------------------------- ### Enable Recommended Serverless Monitor (Default) Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/README.md To create a recommended monitor with default values, define its serverless monitor ID without specifying any additional parameters. Ensure DATADOG_API_KEY and DATADOG_APP_KEY are set in your environment. ```yaml custom: datadog: addLayers: true monitors: - high_error_rate: ``` -------------------------------- ### Run Unit Tests with npm Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/00-index.md Execute the unit test suite for the Datadog Serverless Plugin. ```bash npm test ``` -------------------------------- ### Create SimpleGit Instance Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Creates a configured SimpleGit instance. Returns undefined if not in a git repository. Initializes SimpleGit with the current working directory and attempts to find the git repository root. ```typescript export const newSimpleGit = async (): Promise ``` -------------------------------- ### ServerlessPlugin Constructor Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/02-api-reference-main.md Initializes the ServerlessPlugin with the Serverless framework instance and options. ```APIDOC ## Constructor ServerlessPlugin ### Description Initializes the main plugin class that integrates with the Serverless Framework. This is the entry point for all plugin functionality. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ### Error Handling None ``` -------------------------------- ### Configure Recommended Serverless Monitor Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/README.md To customize a recommended monitor, define its serverless monitor ID and specify parameters like name, message, tags, and thresholds. Parameters not explicitly set will use their default recommended values. Ensure DATADOG_API_KEY and DATADOG_APP_KEY are set in your environment. ```yaml custom: datadog: addLayers: true monitors: - high_error_rate: name: "High Error Rate with Modified Warning Threshold" message: "More than 10% of the function's invocations were errors in the selected time range. Notify @data.dog@datadoghq.com @slack-serverless-monitors" tags: ["modified_error_rate", "serverless", "error_rate"] require_full_window: true priority: 2 options: include_tags: true notify_audit: true thresholds: warning: 0.05 critical: 0.1 ``` -------------------------------- ### Enable and Configure Custom Serverless Monitor Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/README.md To define a custom monitor, provide a unique serverless monitor ID and the required `query` parameter. Other parameters like name, message, tags, and options can be specified as needed. Ensure DATADOG_API_KEY and DATADOG_APP_KEY are set in your environment. ```yaml custom: datadog: addLayers: true monitors: - custom_monitor_id: name: "Custom Monitor" query: "max(next_1w):forecast(avg:system.load.1{*}, 'linear', 1, interval='60m', history='1w', model='default') >= 3" message: "Custom message for custom monitor. Notify @data.dog@datadoghq.com @slack-serverless-monitors" tags: ["custom_monitor", "serverless"] priority: 3 options: enable_logs_sample: true require_full_window: true include_tags: false notify_audit: true notify_no_data: false thresholds: warning: 2 critical: 3 ``` -------------------------------- ### Find Lambda Handlers Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/05-api-reference-layer.md Discovers all Lambda functions in a Serverless service, excluding specified ones. Use this to get a list of functions to which layers should be applied. ```typescript export function findHandlers( service: Service, exclude: string[], defaultRuntime?: string ): FunctionInfo[] ``` ```typescript const handlers = findHandlers(service, ["dev-function"], "nodejs20.x"); // Returns functions with supported runtimes, excluding "dev-function" ``` -------------------------------- ### Run Integration Tests with npm Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/00-index.md Execute the integration test suite for the Datadog Serverless Plugin. ```bash npm run test:integration ``` -------------------------------- ### inspectAndRecommendStepFunctionsInstrumentation Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Inspects the Serverless Framework configuration for the presence of Step Functions and recommends enabling instrumentation if they are found but not already configured. This function logs recommendations directly to the console. ```APIDOC ## inspectAndRecommendStepFunctionsInstrumentation ### Description Recommends enabling Step Functions instrumentation if Step Functions are present in the service and instrumentation is not enabled. Logs recommendations to the console. ### Method Not applicable (function signature provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **serverless** (`Serverless`) - Required - Serverless framework instance ### Response #### Success Response - Returns `void` (logs to console). ### Response Example (No return value, logs to console) ``` -------------------------------- ### isStepFunctionInvocation Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Determines if a Step Functions resource ARN indicates that the step invokes another Step Function. It specifically checks for the ARN pattern used for starting Step Function executions. ```APIDOC ## isStepFunctionInvocation ### Description Checks if a Step Function step invokes another Step Function. ### Method Not applicable (function signature provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **resource** (`string | undefined`) - Required - Step resource ARN ### Response #### Success Response - Returns `true` if the resource is a Step Function invocation, `false` otherwise. ### Response Example `true` or `false` ``` -------------------------------- ### ServerlessPlugin Constructor Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/02-api-reference-main.md Initializes the ServerlessPlugin with the Serverless framework instance and options. ```typescript constructor( private serverless: Serverless, private options: Serverless.Options, ) ``` -------------------------------- ### Configure Datadog Serverless Plugin Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/README.md Add a `custom` > `datadog` section to your `serverless.yml` to configure the plugin. Ensure you provide your API key or SSM ARN. ```yaml custom: datadog: apiKeySecretArn: "{Datadog_API_Key_Secret_ARN}" # or use apiKeySsmArn for AWS Systems Manager Parameter Store enableXrayTracing: false enableDDTracing: true enableDDLogs: true subscribeToAccessLogs: true forwarderArn: arn:aws:lambda:us-east-1:000000000000:function:datadog-forwarder exclude: - dd-excluded-function ``` -------------------------------- ### buildMonitorParams Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md Builds complete monitor parameters from user configuration and recommended templates, preparing them for API requests. ```APIDOC ## buildMonitorParams ### Description Builds complete monitor parameters from user configuration and recommended templates. ### Signature ```typescript export function buildMonitorParams( monitor: Monitor, cloudFormationStackId: string, service: string, env: string, recommendedMonitors: RecommendedMonitors ): MonitorParams ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Description | |-----------|------|-------------| | monitor | `Monitor` | User-provided monitor config with serverless monitor ID as key | | cloudFormationStackId | `string` | CloudFormation stack ID for tagging | | service | `string` | Service name for tagging | | env | `string` | Environment name for tagging | | recommendedMonitors | `RecommendedMonitors` | Templates from Datadog API | ### Returns `MonitorParams` ready for API request ### Behavior - Extracts serverless monitor ID from the monitor object key - Merges user-provided options with recommended template - Sets default monitor type to "metric alert" - Adds required tags: - `serverless_monitor_type:single_function` - `serverless_monitor_id:{id}` - `aws_cloudformation_stack-id:{stackId}` - `created_by:dd_sls_plugin` - `env:{env}` - `service:{service}` - For recommended monitors: - Uses recommendation query (or user-provided override) - Uses recommendation message (or user-provided override) - Allows user to override critical threshold - Returns complete parameters ready for API ### Example ```typescript const params = buildMonitorParams( { high_error_rate: { options: { thresholds: { critical: 0.15 } } } }, "arn:aws:cloudformation:us-east-1:123456789012:stack/my-stack/xxx", "my-service", "production", recommendedMonitors ); // Returns MonitorParams with: // - query tailored to the stack // - tags including service and environment // - threshold set to 0.15 (overriding default) ``` ``` -------------------------------- ### Order of Plugins in serverless.yml Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/README.md Ensure serverless-plugin-datadog is listed after serverless-plugin-warmup in your serverless.yml to properly package your application. ```yaml plugins: - serverless-plugin-warmup - serverless-plugin-datadog ``` -------------------------------- ### Generate Coverage Report with npm Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/00-index.md Generate a code coverage report for the Datadog Serverless Plugin. ```bash npm run coverage ``` -------------------------------- ### newSimpleGit Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Creates a configured SimpleGit instance for git operations. It initializes SimpleGit, finds the git repository root, and updates the base directory for relative path resolution. Returns undefined if not in a git repository. ```APIDOC ## newSimpleGit ### Description Creates a configured SimpleGit instance for git operations. ### Method ```typescript export const newSimpleGit = async (): Promise ``` ### Returns SimpleGit instance if successful, `undefined` if not in a git repository. ### Behavior - Initializes SimpleGit with baseDir set to current working directory - Attempts to find the git repository root using `git rev-parse --show-toplevel` - Updates baseDir to repository root for relative path resolution - Returns `undefined` if the current directory is not in a git repository ### Example ```typescript const git = await newSimpleGit(); if (git && await git.checkIsRepo()) { const commit = await git.log(['-1', '--format=%H']); console.log(commit); } ``` ``` -------------------------------- ### Minimal Datadog Plugin Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/00-index.md Use this minimal configuration for basic Datadog integration. It sets the Datadog site and uses an environment variable for the API key. ```yaml custom: datadog: site: datadoghq.com apiKey: ${env:DATADOG_API_KEY} ``` -------------------------------- ### Serverless Plugin Datadog Commands Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/01-overview.md Custom Serverless CLI commands for managing Datadog instrumentation. Use 'clean' to remove wrappers and 'generate' to create them. ```bash serverless datadog clean ``` ```bash serverless datadog generate ``` -------------------------------- ### Run Unit Tests Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/CONTRIBUTING.md Execute the project's unit tests to ensure code integrity. ```bash yarn test ``` -------------------------------- ### Recommend Step Functions Instrumentation Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Scans the Serverless service configuration for defined Step Functions. If Step Functions are found and instrumentation is not enabled, it logs a recommendation to enable it. ```typescript export function inspectAndRecommendStepFunctionsInstrumentation( serverless: Serverless ): void ``` -------------------------------- ### Build Monitor Parameters Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md Constructs complete monitor parameters by merging user configuration with recommended templates. It extracts the serverless monitor ID, sets default monitor types, and adds essential tags for CloudFormation stacks, services, and environments. This function is useful for preparing monitor configurations before sending them to the Datadog API. ```typescript export function buildMonitorParams( monitor: Monitor, cloudFormationStackId: string, service: string, env: string, recommendedMonitors: RecommendedMonitors ): MonitorParams ``` ```typescript const params = buildMonitorParams( { high_error_rate: { options: { thresholds: { critical: 0.15 } } } }, "arn:aws:cloudformation:us-east-1:123456789012:stack/my-stack/xxx", "my-service", "production", recommendedMonitors ); // Returns MonitorParams with: // - query tailored to the stack // - tags including service and environment // - threshold set to 0.15 (overriding default) ``` -------------------------------- ### StepFunctionConfig Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/06-api-reference-forwarder.md Step Function configuration from serverless-step-functions plugin. ```APIDOC ## Interface: StepFunctionConfig ### Description Step Function configuration from serverless-step-functions plugin. ### Fields - **name** (string) - Step Function name - **loggingConfig** (StepFunctionLoggingConfig) - Logging configuration with level and destinations ``` -------------------------------- ### ServerlessMonitor Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md A recommended monitor template fetched from Datadog's API. It includes details like name, threshold, query generation function, message, and optional type and template variables. ```APIDOC ## Interface: ServerlessMonitor ### Description A recommended monitor template fetched from Datadog's API. ### Fields #### name - **Type**: `string` - **Description**: Monitor name template #### threshold - **Type**: `number` - **Description**: Default critical threshold #### query - **Type**: `function` - **Description**: Function generating the metric query #### message - **Type**: `string` - **Description**: Alert message template #### type - **Type**: `string` - **Description**: Monitor type (e.g., "metric alert") #### templateVariables - **Type**: `TemplateVariable[]` - **Description**: Variables that can be substituted in the name ``` -------------------------------- ### printOutputs Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Prints CloudFormation outputs and Datadog monitor links to the console, formatted for readability. ```APIDOC ## printOutputs ### Description Prints CloudFormation outputs and monitor links to the console. ### Signature ```typescript export async function printOutputs( serverless: Serverless, site: string, subdomain: string, service: string, env: string ): Promise ``` ### Parameters - **serverless** (`Serverless`): Serverless framework instance. - **site** (`string`): Datadog site domain. - **subdomain** (`string`): Datadog subdomain. - **service** (`string`): Service name. - **env** (`string`): Environment name. ### Behavior - Fetches CloudFormation stack outputs. - Prints formatted output with two sections: 1. "Datadog Monitoring" > "functions": Lists function links. 2. "View Serverless Monitors": Links to monitors filtered by service and environment. - Uses colored output (yellow, orange) for formatting. ### Returns void (writes to console) ### Output Example ``` Datadog Monitoring functions myFunction: https://app.datadoghq.com/functions?... View Serverless Monitors https://app.datadoghq.com/monitors/manage?q=tag:(... ``` ``` -------------------------------- ### Full Featured Datadog Plugin Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/00-index.md This comprehensive configuration enables advanced features like adding layers and extensions, enabling tracing and logging, integrating source code, subscribing to access logs, and setting up monitors. It also allows for custom service, environment, and tags. ```yaml custom: datadog: site: datadoghq.com apiKey: ${env:DATADOG_API_KEY} appKey: ${env:DATADOG_APP_KEY} addLayers: true addExtension: true enableDDTracing: true enableDDLogs: true enableSourceCodeIntegration: true subscribeToAccessLogs: true forwarderArn: arn:aws:lambda:region:account:function:Datadog-Log-Forwarder monitors: - high_error_rate: {} - timeout: {} env: production service: my-service tags: "team:backend,cost-center:engineering" enableStepFunctionsTracing: true ``` -------------------------------- ### enableTracing Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Configures tracing mode on Lambda functions, enabling X-Ray and/or Datadog tracing based on the specified mode. ```APIDOC ## enableTracing ### Description Configures tracing mode on Lambda functions. ### Signature ```typescript export function enableTracing( service: Service, tracingMode: TracingMode, handlers: FunctionInfo[] ): void ``` ### Parameters - **service** (`Service`): Serverless service object. - **tracingMode** (`TracingMode`): Desired tracing mode. Possible values are `XRAY`, `DD_TRACE`, `HYBRID`, `NONE`. - **handlers** (`FunctionInfo[]`): Function handlers to configure. ### Behavior - If `tracingMode` is XRAY or HYBRID: - Enables X-Ray tracing on Lambda functions. - Enables X-Ray tracing on API Gateway (if not using custom REST API ID). - For all handlers: - If `DD_TRACE_ENABLED` is false and X-Ray is enabled, sets `DD_MERGE_XRAY_TRACES` to false. ### Returns void (modifies service in place) ``` -------------------------------- ### Configuration Interface Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/04-api-reference-env.md The main configuration interface for the Datadog plugin, detailing all available configuration options. ```APIDOC ## Interface: Configuration ### Description Main configuration interface for the Datadog plugin. ### Fields - `enabled` (boolean) - Optional - Whether the Datadog plugin is enabled. - `addLayers` (boolean) - Required - Whether to add Datadog layers to Lambda functions. - `apiKey` (string) - Optional - Datadog API key. - `appKey` (string) - Optional - Datadog Application Key. - `monitorsApiKey` (string) - Optional - Datadog Monitors API key. - `monitorsAppKey` (string) - Optional - Datadog Monitors Application Key. - `apiKeySecretArn` (string) - Optional - ARN of the Secrets Manager secret containing the API key. - `apiKeySsmArn` (string) - Optional - ARN of the Systems Manager Parameter Store parameter containing the API key. - `apiKMSKey` (string) - Optional - KMS key used for encrypting API keys. - `captureLambdaPayload` (boolean) - Optional - Whether to capture Lambda function payloads. - `site` (string) - Required - The Datadog site to send data to (e.g., 'datadoghq.com'). - `subdomain` (string) - Required - The subdomain for the Datadog site. - `logLevel` (string | undefined) - Required - The logging level for the plugin. - `flushMetricsToLogs` (boolean) - Required - Whether to flush metrics to logs. - `enableXrayTracing` (boolean) - Required - Whether to enable AWS X-Ray tracing. - `enableDDTracing` (boolean) - Required - Whether to enable Datadog tracing. - `appSecMode` (AppSecMode) - Optional - Configuration mode for AppSec. - `enableASM` (boolean) - Optional - Whether to enable Application Security Management (ASM). - `enableDDLogs` (boolean) - Required - Whether to enable Datadog logs. - `enableProfiling` (boolean) - Optional - Whether to enable profiling. - `addExtension` (boolean) - Required - Whether to add the Datadog Lambda Extension. - `forwarderArn` (string) - Optional - ARN of the Lambda forwarder function. - `forwarder` (string) - Optional - Name of the Lambda forwarder function. - `testingMode` (boolean) - Optional - Whether to enable testing mode. - `integrationTesting` (boolean) - Optional - Whether to enable integration testing. - `enableTags` (boolean) - Required - Whether to enable tagging. - `injectLogContext` (boolean) - Required - Whether to inject log context. - `enableSourceCodeIntegration` (boolean) - Required - Whether to enable source code integration. - `uploadGitMetadata` (boolean) - Required - Whether to upload Git metadata. - `exclude` (string[]) - Required - List of paths to exclude from instrumentation. - `monitors` (Record>[]) - Optional - Configuration for Datadog monitors. - `failOnError` (boolean) - Required - Whether to fail on errors. - `subscribeToAccessLogs` (boolean) - Required - Whether to subscribe to access logs. - `subscribeToExecutionLogs` (boolean) - Required - Whether to subscribe to execution logs. - `subscribeToStepFunctionLogs` (boolean) - Required - Whether to subscribe to Step Functions logs. - `skipCloudformationOutputs` (boolean) - Required - Whether to skip CloudFormation outputs. - `customHandler` (string) - Optional - Path to a custom Lambda handler. - `enableColdStartTracing` (boolean) - Optional - Whether to enable cold start tracing. - `minColdStartTraceDuration` (number) - Optional - Minimum duration for cold start traces. - `coldStartTraceSkipLibs` (string) - Optional - Libraries to skip during cold start tracing. - `encodeAuthorizerContext` (boolean) - Optional - Whether to encode authorizer context. - `decodeAuthorizerContext` (boolean) - Optional - Whether to decode authorizer context. - `apmFlushDeadline` (string | number) - Optional - Deadline for APM flush. - `useLayersFromAccount` (string) - Optional - Account ID to use for layers. - `enableStepFunctionsTracing` (boolean) - Optional - Whether to enable Step Functions tracing. - `mergeStepFunctionAndLambdaTraces` (boolean) - Optional - Whether to merge Step Functions and Lambda traces. - `propagateTraceContext` (boolean) - Optional - Whether to propagate trace context. - `propagateUpstreamTrace` (boolean) - Optional - Whether to propagate upstream trace. - `redirectHandlers` (boolean) - Optional - Whether to redirect handlers. - `isFIPSEnabled` (boolean) - Optional - Whether FIPS is enabled. - `llmObsEnabled` (boolean) - Optional - Whether LLM observability is enabled. - `llmObsMlApp` (string) - Optional - The ML application for LLM observability. - `llmObsAgentlessEnabled` (boolean) - Optional - Whether agentless LLM observability is enabled. ### Source `src/env.ts:16-147` ``` -------------------------------- ### RecommendedMonitors Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md Map of serverless monitor IDs to their definitions. This type represents a collection of recommended monitor configurations. ```APIDOC ## Type Alias: RecommendedMonitors ### Description Map of serverless monitor IDs to their definitions. ### Example ```json { "high_error_rate": { ... }, "timeout": { ... }, "out_of_memory": { ... } } ``` ``` -------------------------------- ### ServerlessMonitor Interface Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/09-types.md Represents a recommended monitor template from the Datadog API. It includes a name, threshold, a function to generate the query, message, and optional type and template variables. ```typescript interface ServerlessMonitor { name: string; threshold: number; query: (cloudFormationStackId: string, criticalThreshold: number) => string; message: string; type?: string; templateVariables?: TemplateVariable[]; } ``` -------------------------------- ### ServerlessMonitor Interface Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md Represents a recommended monitor template fetched from Datadog's API. It includes fields for name, default threshold, a query generation function, message template, and optional type and template variables. ```typescript export interface ServerlessMonitor { name: string; threshold: number; query: (cloudFormationStackId: string, criticalThreshold: number) => string; message: string; type?: string; templateVariables?: TemplateVariable[]; } ``` -------------------------------- ### StateMachineCfnResource Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/06-api-reference-forwarder.md CloudFormation resource definition for AWS::StepFunctions::StateMachine. ```APIDOC ## Interface: StateMachineCfnResource ### Description CloudFormation resource definition for AWS::StepFunctions::StateMachine. ### Fields - **Properties** (object) - CloudFormation resource properties - **Properties.Tags** (Array<{Key, Value}>) - Resource tags ``` -------------------------------- ### getConfig Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/04-api-reference-env.md Extracts and merges the Datadog configuration from the Serverless service object with defaults. It reads `custom.datadog` and applies default values, also handling deprecated API key options. ```APIDOC ## getConfig ### Description Extracts and merges the Datadog configuration from the Serverless service object with defaults. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```typescript export function getConfig(service: Service): Configuration ``` ### Returns `Configuration` object with user-provided values merged over defaults. ### Example ```typescript import { getConfig } from './env'; import Service from 'serverless/classes/Service'; const config = getConfig(service); console.log(config.site); // "datadoghq.com" console.log(config.addExtension); // true (default) ``` ``` -------------------------------- ### ForwarderConfigs Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/06-api-reference-forwarder.md Configuration flags for forwarder subscription behavior. ```APIDOC ## Interface: ForwarderConfigs ### Description Configuration flags for forwarder subscription behavior. ### Fields - **AddExtension** (boolean) - Whether Lambda Extension is enabled (affects which log groups to subscribe) - **TestingMode** (boolean) - Skip validation checks when true - **IntegrationTesting** (boolean) - Legacy name for testing mode - **SubToAccessLogGroups** (boolean) - Subscribe to API Gateway access log groups - **SubToExecutionLogGroups** (boolean) - Subscribe to REST API and WebSocket execution log groups - **SubToStepFunctionLogGroups** (boolean) - Subscribe to Step Functions log groups ``` -------------------------------- ### ServerlessPlugin Commands Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/02-api-reference-main.md Registers custom CLI commands 'serverless datadog clean' and 'serverless datadog generate' for Datadog instrumentation. ```typescript public commands = { datadog: { commands: { clean: { lifecycleEvents: ["init"], usage: "Cleans up wrapper handler functions for DataDog, not necessary in most cases", }, generate: { lifecycleEvents: ["init"], usage: "Generates wrapper handler functions for DataDog, not necessary in most cases", }, }, lifecycleEvents: ["clean", "generate"], usage: "Automatically instruments your lambdas with DataDog", }, } ``` -------------------------------- ### FunctionInfo Interface Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/05-api-reference-layer.md Information about a Lambda function discovered in the Serverless configuration. ```APIDOC ## Interface: FunctionInfo ```typescript export interface FunctionInfo { name: string; type: RuntimeType; handler: ExtendedFunctionDefinition; runtime?: string; } ``` Information about a Lambda function discovered in the Serverless configuration. **Fields:** | Field | Type | Description | |-------|------|-------------| | name | `string` | Function name as defined in serverless.yml | | type | `RuntimeType` | Detected runtime type from the runtime string | | handler | `ExtendedFunctionDefinition` | Function definition object | | runtime | `string` | Runtime identifier (e.g., "nodejs20.x", "python3.11") | ``` -------------------------------- ### ServerlessPlugin Public Properties Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/02-api-reference-main.md Exposes hooks for Serverless Framework lifecycle events and registers custom CLI commands. ```APIDOC ## Public Properties ServerlessPlugin ### Description Exposes properties that define the plugin's behavior, including its command registrations and lifecycle event hooks. ### Properties #### hooks Maps Serverless Framework lifecycle events to handler methods. #### commands Registers custom CLI commands `serverless datadog clean` and `serverless datadog generate`. ``` -------------------------------- ### Set Datadog Monitors Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/07-api-reference-monitors.md Manages the creation, update, and deletion of Datadog monitors based on the serverless configuration. It first fetches recommended monitor templates and existing monitors, then processes each configured monitor. This function is essential for synchronizing your infrastructure's monitors with your serverless application's needs. ```typescript export async function setMonitors( subdomain: string, site: string, monitors: Monitor[], monitorsApiKey: string, monitorsAppKey: string, cloudFormationStackId: string, service: string, env: string ): Promise ``` ```typescript const messages = await setMonitors( "app", "datadoghq.com", [ { high_error_rate: {} }, { timeout: { threshold: 60 } } ], "apiKey", "appKey", "arn:aws:cloudformation:…", "my-service", "production" ); messages.forEach(msg => console.log(msg)); // Output: // Successfully created high_error_rate // Successfully updated timeout ``` -------------------------------- ### Default Plugin Configuration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/03-configuration.md This object defines the default configuration values for the Datadog Serverless Plugin. These defaults are applied if no specific configuration is provided by the user. ```typescript export const defaultConfiguration: Configuration = { addLayers: true, flushMetricsToLogs: true, logLevel: undefined, site: "datadoghq.com", subdomain: "app", enableXrayTracing: false, enableDDTracing: true, addExtension: true, enableTags: true, injectLogContext: true, enableSourceCodeIntegration: true, uploadGitMetadata: true, exclude: [], testingMode: false, integrationTesting: false, subscribeToAccessLogs: true, subscribeToExecutionLogs: false, subscribeToStepFunctionLogs: false, enableDDLogs: true, captureLambdaPayload: false, failOnError: false, skipCloudformationOutputs: false, mergeStepFunctionAndLambdaTraces: false, propagateTraceContext: false, propagateUpstreamTrace: false, enableStepFunctionsTracing: false, redirectHandlers: true, }; ``` -------------------------------- ### Configuration Interface for Datadog Plugin Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/09-types.md The complete configuration interface for the Datadog plugin. This interface outlines all available settings for enabling and customizing the plugin's features. ```typescript interface Configuration { enabled: boolean; site: string; subdomain: string; apiKey: string; appKey: string; addLayers: boolean; addExtension: boolean; enableDDTracing: boolean; enableDDLogs: boolean; enableXrayTracing: boolean; forwarderArn: string; enableSourceCodeIntegration: boolean; uploadGitMetadata: boolean; exclude: string[]; monitors: Record>[]; appSecMode: AppSecMode; enableStepFunctionsTracing: boolean; isFIPSEnabled: boolean; } ``` -------------------------------- ### enableTracing Function Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/08-api-reference-utilities.md Configures tracing mode on Lambda functions. Call this function to enable X-Ray, Datadog tracing, or both. ```typescript export function enableTracing( service: Service, tracingMode: TracingMode, handlers: FunctionInfo[] ): void ``` -------------------------------- ### applyExtensionLayer Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/05-api-reference-layer.md Adds the Datadog Lambda Extension layer to all specified functions. It handles architecture detection and can apply FIPS-compliant layers if needed, also supporting local layer ARNs. ```APIDOC ## applyExtensionLayer ### Description Adds the Datadog Lambda Extension layer to all functions. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **service** (`Service`) - Serverless service object - **handlers** (`FunctionInfo[]`) - Array of function handlers to update - **layers** (`LayerJSON`) - Layer definitions - **accountId** (`string`, optional) - Optional AWS account ID for local layers - **isFIPSEnabled** (`boolean`, optional) - If true, use FIPS-compliant extension layer ### Returns `void` - Modifies the service object in place. ### Behavior - For each function: - Detects architecture (x86_64 or arm64) - Selects extension layer key, optionally appending "-fips" - For ARM64, uses "extension-arm" or "extension-arm-fips" - Removes previous extension layer if switching architectures - Builds local ARN if accountId provided - Adds extension layer to function's layers array ``` -------------------------------- ### ServerlessPlugin Hooks Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/02-api-reference-main.md Maps Serverless Framework lifecycle events to internal handler methods for Datadog integration. ```typescript public hooks = { initialize: this.cliSharedInitialize.bind(this), "after:datadog:clean:init": this.afterPackageFunction.bind(this), "after:datadog:generate:init": this.beforePackageFunction.bind(this), "after:deploy:function:packageFunction": this.afterPackageFunction.bind(this), "after:package:createDeploymentArtifacts": this.afterPackageFunction.bind(this), "before:package:createDeploymentArtifacts": this.beforePackageFunction.bind(this), "after:package:compileFunctions": this.afterPackageCompileFunctions.bind(this), "before:deploy:function:packageFunction": this.beforePackageFunction.bind(this), "before:offline:start:init": this.beforePackageFunction.bind(this), "before:step-functions-offline:start": this.beforePackageFunction.bind(this), "before:deploy:deploy": this.beforeDeploy.bind(this), "after:deploy:deploy": this.afterDeploy.bind(this), "before:package:finalize": this.afterPackageFunction.bind(this), } ``` -------------------------------- ### Add Datadog Plugin to Serverless TypeScript Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/README.md When using serverless-typescript, ensure `serverless-datadog` is listed before `serverless-typescript` in your `serverless.yml` to allow automatic detection of `.ts` files. ```yaml plugins: - serverless-plugin-datadog - serverless-typescript ``` -------------------------------- ### StepFunctionConfig Interface Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/06-api-reference-forwarder.md Step Function configuration from serverless-step-functions plugin. This interface defines the structure for configuring Step Functions, including their name and logging configuration. ```typescript export interface StepFunctionConfig { name: string; loggingConfig?: StepFunctionLoggingConfig; } ``` -------------------------------- ### setEnvConfiguration Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/04-api-reference-env.md Sets environment variables on all Lambda functions based on the Datadog configuration. This is the primary function for applying configuration to Lambda functions. ```APIDOC ## setEnvConfiguration ### Description Sets environment variables on all Lambda functions based on the Datadog configuration. This is the primary function that applies configuration to actual Lambda functions. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **config** (`Configuration`) - Plugin configuration object. - **handlers** (`FunctionInfo[]`) - Array of Lambda function handlers to configure. ### Method Signature ```typescript export function setEnvConfiguration( config: Configuration, handlers: FunctionInfo[] ): void ``` ### Behavior Applies the following environment variables to each function based on configuration: | Environment Variable | |----------------------| | `DD_API_KEY` | | `DD_KMS_API_KEY` | | `DD_API_KEY_SECRET_ARN` | | `DD_API_KEY_SSM_ARN` | | `DD_SITE` | | `DD_LOG_LEVEL` | | `DD_FLUSH_TO_LOG` | | `DD_TRACE_ENABLED` | | `DD_MERGE_XRAY_TRACES` | | `DD_LOGS_INJECTION` | | `DD_SERVERLESS_LOGS_ENABLED` | | `DD_CAPTURE_LAMBDA_PAYLOAD` | | `DD_COLD_START_TRACING` | | `DD_MIN_COLD_START_DURATION` | | `DD_COLD_START_TRACE_SKIP_LIB` | | `DD_PROFILING_ENABLED` | | `DD_ENCODE_AUTHORIZER_CONTEXT` | | `DD_DECODE_AUTHORIZER_CONTEXT` | | `DD_APM_FLUSH_DEADLINE_MILLISECONDS` | | `DD_USE_LAYERS_FROM_ACCOUNT` | | `AWS_LAMBDA_EXEC_WRAPPER` | | `DD_SERVERLESS_APPSEC_ENABLED` | | `DD_APPSEC_ENABLED` | | `DD_LLMOBS_ENABLED` | | `DD_LLMOBS_ML_APP` | | `DD_LLMOBS_AGENTLESS_ENABLED` | ### Throws - `Error` if multiple API key methods are set simultaneously. - `Error` if `apiKeySecretArn` is used with Node.js and synchronous metrics. - `Error` if `appSecMode` has invalid value. - `Error` if `appSecMode` and `enableASM` are both set. - `Error` if `appSecMode` is set without `enableDDTracing`. - `Error` if `appSecMode: "tracer"` is used with non-Python runtime. - `Error` if `llmObsEnabled: true` without `llmObsMlApp`. - `Error` if `llmObsMlApp` has invalid format. ``` -------------------------------- ### StepFunctionConfig Interface Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/09-types.md Defines the configuration for a Step Function, including its name and logging settings. Specify the Step Function's name and optionally its logging configuration. ```typescript interface StepFunctionConfig { name: string; loggingConfig?: StepFunctionLoggingConfig; } ``` -------------------------------- ### ARM Runtime Keys Map Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/05-api-reference-layer.md Maps x86_64 layer keys to their ARM64 equivalents in layers.json. Node.js and Java use the same layers for both architectures. Use this to find the correct layer key for ARM64 deployments. ```typescript export const ARM_RUNTIME_KEYS: Record = { "python3.8": "python3.8-arm", "python3.9": "python3.9-arm", "python3.10": "python3.10-arm", "python3.11": "python3.11-arm", "python3.12": "python3.12-arm", "python3.13": "python3.13-arm", "python3.14": "python3.14-arm", "ruby3.2": "ruby3.2-arm", "ruby3.3": "ruby3.3-arm", "ruby3.4": "ruby3.4-arm", "ruby4.0": "ruby4.0-arm", extension: "extension-arm", dotnet: "dotnet-arm", "nodejs16.x": "nodejs16.x", "nodejs18.x": "nodejs18.x", "nodejs20.x": "nodejs20.x", "nodejs22.x": "nodejs22.x", "nodejs24.x": "nodejs24.x", java: "java", } ``` -------------------------------- ### Check for Webpack Plugin Source: https://github.com/datadog/serverless-plugin-datadog/blob/main/_autodocs/04-api-reference-env.md Detects whether the serverless-webpack plugin is configured in the project. Returns true if configured, false otherwise. ```typescript export function hasWebpackPlugin(service: Service): boolean ```