UNPKG

@aws-lambda-powertools/metrics

Version:
274 lines 10.6 kB
import { Utility } from '@aws-lambda-powertools/commons'; import { MetricsInterface } from '.'; import { MetricsOptions, Dimensions, EmfOutput, HandlerMethodDecorator, ExtraOptions, MetricUnit, MetricUnits, MetricResolution } from './types'; /** * ## Intro * Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF). * * These metrics can be visualized through Amazon CloudWatch Console. * * ## Key features * * Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob) * * Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc) * * Metrics are created asynchronously by CloudWatch service, no custom stacks needed * * Context manager to create a one off metric with a different dimension * * ## Usage * * ### Functions usage with middleware * * Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error. * Additionally, you can configure the middleware to easily: * * ensure that at least one metric is emitted before you flush them * * capture a `ColdStart` a metric * * set default dimensions for all your metrics * * @example * ```typescript * import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics'; * import middy from '@middy/core'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); * * const lambdaHandler = async (_event: any, _context: any) => { * ... * }; * * export const handler = middy(lambdaHandler).use(logMetrics(metrics)); * ``` * * ### Object oriented way with decorator * * If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically: * * capture a `ColdStart` metric * * flush buffered metrics * * throw on empty metrics * * @example * * ```typescript * import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; * import { LambdaInterface } from '@aws-lambda-powertools/commons'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); * * class Lambda implements LambdaInterface { * * // FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/47679 and might show as *@metrics* instead of `@metrics.logMetrics` * * @metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true }) * public handler(_event: any, _context: any): Promise<void> { * // ... * metrics.addMetric('test-metric', MetricUnits.Count, 10); * // ... * } * } * * const handlerClass = new Lambda(); * export const handler = handlerClass.handler.bind(handlerClass); * ``` * * ### Standard function * * If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics. * * @example * * ```typescript * import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); * * export const handler = async (_event: any, _context: any): Promise<void> => { * metrics.captureColdStartMetric(); * metrics.addMetric('test-metric', MetricUnits.Count, 10); * metrics.publishStoredMetrics(); * }; * ``` */ declare class Metrics extends Utility implements MetricsInterface { private customConfigService?; private defaultDimensions; private dimensions; private envVarsService?; private functionName?; private isSingleMetric; private metadata; private namespace?; private shouldThrowOnEmptyMetrics; private storedMetrics; constructor(options?: MetricsOptions); /** * Add a dimension to the metrics. * A dimension is a key-value pair that is used to group metrics. * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details. * @param name * @param value */ addDimension(name: string, value: string): void; /** * Add multiple dimensions to the metrics. * @param dimensions */ addDimensions(dimensions: { [key: string]: string; }): void; /** * A high-cardinality data part of your Metrics log. This is useful when you want to search highly contextual information along with your metrics in your logs. * @param key * @param value */ addMetadata(key: string, value: string): void; /** * Add a metric to the metrics buffer. * * @example * * Add Metric using MetricUnit Enum supported by Cloudwatch * * ```ts * metrics.addMetric('successfulBooking', MetricUnits.Count, 1); * ``` * * @example * * Add Metric using MetricResolution type with resolutions High or Standard supported by cloudwatch * * ```ts * metrics.addMetric('successfulBooking', MetricUnits.Count, 1, MetricResolution.High); * ``` * * @param name - The metric name * @param unit - The metric unit * @param value - The metric value * @param resolution - The metric resolution * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition Amazon Cloudwatch Concepts Documentation * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html#CloudWatch_Embedded_Metric_Format_Specification_structure_metricdefinition Metric Definition of Embedded Metric Format Specification */ addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void; /** * Create a singleMetric to capture cold start. * If it's a cold start invocation, this feature will: * * Create a separate EMF blob solely containing a metric named ColdStart * * Add function_name and service dimensions * * This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions. * * @example * * ```typescript * import { Metrics } from '@aws-lambda-powertools/metrics'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); * * export const handler = async (event: any, _context: any): Promise<void> => { * metrics.captureColdStartMetric(); * }; * ``` */ captureColdStartMetric(): void; clearDefaultDimensions(): void; clearDimensions(): void; clearMetadata(): void; clearMetrics(): void; /** * A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit. * * @example * * ```typescript * import { Metrics } from '@aws-lambda-powertools/metrics'; * import { LambdaInterface } from '@aws-lambda-powertools/commons'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); * * class Lambda implements LambdaInterface { * * @metrics.logMetrics({ captureColdStartMetric: true }) * public handler(_event: any, _context: any): Promise<void> { * // ... * } * } * * const handlerClass = new Lambda(); * export const handler = handlerClass.handler.bind(handlerClass); * ``` * * @decorator Class */ logMetrics(options?: ExtraOptions): HandlerMethodDecorator; /** * Synchronous function to actually publish your metrics. (Not needed if using logMetrics decorator). * It will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation. * * @example * * ```typescript * import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension * * export const handler = async (_event: any, _context: any): Promise<void> => { * metrics.addMetric('test-metric', MetricUnits.Count, 10); * metrics.publishStoredMetrics(); * }; * ``` */ publishStoredMetrics(): void; /** * Function to create the right object compliant with Cloudwatch EMF (Embedded Metric Format). * * * @returns metrics as JSON object compliant EMF Schema Specification * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html for more details */ serializeMetrics(): EmfOutput; setDefaultDimensions(dimensions: Dimensions | undefined): void; setFunctionName(value: string): void; /** * CloudWatch EMF uses the same dimensions across all your metrics. Use singleMetric if you have a metric that should have different dimensions. * * You don't need to call publishStoredMetrics() after calling addMetric for a singleMetrics, they will be flushed directly. * * @example * * ```typescript * const singleMetric = metrics.singleMetric(); * singleMetric.addDimension('InnerDimension', 'true'); * singleMetric.addMetric('single-metric', MetricUnits.Percent, 50); * ``` * * @returns the Metrics */ singleMetric(): Metrics; /** * Throw an Error if the metrics buffer is empty. * * @example * * ```typescript * import { Metrics } from '@aws-lambda-powertools/metrics'; * * const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' }); * * export const handler = async (_event: any, _context: any): Promise<void> => { * metrics.throwOnEmptyMetrics(); * metrics.publishStoredMetrics(); // will throw since no metrics added. * }; * ``` */ throwOnEmptyMetrics(): void; private getCurrentDimensionsCount; private getCustomConfigService; private getEnvVarsService; private isHigh; private isNewMetric; private setCustomConfigService; private setEnvVarsService; private setNamespace; private setOptions; private setService; private storeMetric; } export { Metrics, MetricUnits, MetricResolution, }; //# sourceMappingURL=Metrics.d.ts.map