ProtectedcoldProtected ReadonlydefaultLog level used by the current instance of Logger.
Returns the log level as a number. The higher the number, the less verbose the logs. To get the log level name, use the () method.
Add the current Lambda function's invocation context data to the powertoolLogData property of the instance. This context data will be part of all printed log items.
The Lambda function's invocation context.
This method is deprecated and will be removed in the future major versions, please use () appendPersistentKeys() instead.
Add the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.
If the key already exists in the attributes, it will be overwritten. If the key is one of level, message, sampling_rate,
service, or timestamp we will log a warning and drop the value.
The attributes to add to all log items.
Add the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
If the key already exists in the attributes, it will be overwritten. If the key is one of level, message, sampling_rate,
service, or timestamp we will log a warning and drop the value.
The attributes to add to all log items.
ProtectedbufferAdd a log to the buffer.
_X_AMZN_TRACE_ID of the request
Log to be buffered
The level of log to be buffered
Empties the buffer for the current request
ProtectedcreateCreate a log item and populate it with the given log level, input, and extra input.
Create a separate Logger instance, identical to the current one. It's possible to overwrite the new instance options by passing them.
The options to initialize the child logger with.
ProtectedcreateFactory method for instantiating logger instances. Used by createChild method.
Important for customization and subclassing. It allows subclasses, like MyOwnLogger,
to override its behavior while keeping the main business logic in createChild intact.
Optionaloptions: ConstructorOptionsLogger configuration options.
// MyOwnLogger subclass
class MyOwnLogger extends Logger {
protected createLogger(options?: ConstructorOptions): MyOwnLogger {
return new MyOwnLogger(options);
}
// No need to re-implement business logic from `createChild` and keep track on changes
public createChild(options?: ConstructorOptions): MyOwnLogger {
return super.createChild(options) as MyOwnLogger;
}
}
Print a log item with level CRITICAL.
The log message.
The extra input to log.
Print a log item with level DEBUG.
The extra input to log.
Print a log item with level ERROR.
The log message.
The extra input to log.
Flush all logs in the request buffer.
This is called automatically when you use the @logger.injectLambdaContext() decorator and
your function throws an error.
ProtectedgetGet the cold start status of the current execution environment.
The method also flips the cold start status to false after the first invocation.
Get the correlation ID from the log attributes.
ProtectedgetGet the value of the AWS_LAMBDA_INITIALIZATION_TYPE environment variable.
ProtectedgetA custom JSON replacer function that is used to serialize the log items.
By default, we already extend the default serialization behavior to handle BigInt and Error objects, as well as remove circular references.
When a custom JSON replacer function is passed to the Logger constructor, it will be called before our custom rules for each key-value pair in the object being stringified.
This allows you to customize the serialization while still benefiting from the default behavior.
Get the log level name of the current instance of Logger.
Returns the log level name, i.e. INFO, DEBUG, etc.
To get the log level as a number, use the Logger.level property.
Return a boolean value. True means that the Lambda invocation events are printed in the logs.
Return the persistent log attributes, which are the attributes that will be logged in all log items.
Print a log item with level INFO.
The log message.
The extra input to log.
Class method decorator that adds the current Lambda function context as extra information in all log items.
This decorator is useful when you want to enrich your logs with information from the function context, such as the function name, version, and request ID, and more.
Optionaloptions: InjectLambdaContextOptionsOptions for the () method.
OptionalclearState?: booleanUse ()` instead.
OptionalcorrelationIdPath?: stringThe path to the correlation ID in the event object, used to extract the correlation ID from the event object and add it to the log attributes.
OptionalflushBufferOnUncaughtError?: booleanWhether to flush the log buffer when an uncaught error is logged.
OptionallogEvent?: booleanWhen true the logger will log the event.
To avoid logging sensitive information, we recommend using this option only for debugging purposes in local environments.
OptionalresetKeys?: booleanIf true, the logger will reset the keys added via ()
import { Logger } from '@aws-lambda-powertools/logger';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
const logger = new Logger({ serviceName: 'serverlessAirline' });
class Lambda implements LambdaInterface {
// Decorate your handler class method
@logger.injectLambdaContext()
public async handler(_event: unknown, _context: unknown): Promise<void> {
logger.info('This is an INFO log with some context');
}
}
const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);
The decorator can also be used to log the Lambda invocation event; this can be configured both via
the logEvent parameter and the POWERTOOLS_LOGGER_LOG_EVENT environment variable. When both
are set, the logEvent parameter takes precedence.
Additionally, the decorator can be used to reset the temporary keys added with the appendKeys() method
after the invocation, or to flush the buffer when an uncaught error is thrown in the handler.
ProtectedisValidate that the service name provided is valid. Used internally during initialization.
OptionalserviceName: stringService name to validate
Log the AWS Lambda event payload for the current invocation if the environment variable POWERTOOLS_LOGGER_LOG_EVENT is set to true.
The AWS Lambda event payload.
OptionaloverwriteValue: booleanOverwrite the environment variable value.
ProtectedprintPrint a given log with given log level.
The log level
The log item to print
ProtectedprocessPrint or buffer a given log with given log level.
The log level threshold
The log message
The extra input to log
This method allows recalculating the initial sampling decision for changing the log level to DEBUG based on a sample rate value used during initialization, potentially yielding a different outcome.
This only works for warm starts, because we don't to avoid double sampling.
Remove temporary attributes based on provided keys to all log items generated by this Logger instance.
The keys to remove.
Remove the given keys from the persistent keys.
The keys to remove from the persistent attributes.
This method is deprecated and will be removed in the future major versions. Use () instead.
Remove all temporary log attributes added with () appendKeys() method.
Set the correlation ID for the log item.
This method can be used to set the correlation ID for the log item or to search for the correlation ID in the event.
The value to set as the correlation ID or the event to search for the correlation ID
OptionalcorrelationIdPath: stringOptional JMESPath expression to extract the correlation ID for the payload
import { Logger } from '@aws-lambda-powertools/logger';
const logger = new Logger();
logger.setCorrelationId('my-correlation-id'); // sets the correlation ID directly with the first argument as value
import { Logger } from '@aws-lambda-powertools/logger';
import { search } from '@aws-lambda-powertools/logger/correlationId';
const logger = new Logger({ correlationIdSearchFn: search });
logger.setCorrelationId(event, 'requestContext.requestId'); // sets the correlation ID from the event using JMSPath expression
Set the log level for this Logger instance.
If the log level is set using AWS Lambda Advanced Logging Controls, it sets it instead of the given log level to avoid data loss.
The log level to set, i.e. error, warn, info, debug, etc.
This method is deprecated and will be removed in the future major versions, please use () appendPersistentKeys() instead.
ProtectedshouldTest if the log meets the criteria to be buffered.
_X_AMZN_TRACE_ID of the request
The level of the log being considered
Check whether the current Lambda invocation event should be printed in the logs or not.
OptionaloverwriteValue: booleanOverwrite the environment variable value.
Print a log item with level TRACE.
The log message.
The extra input to log.
Print a log item with level WARN.
The log message.
The extra input to log.
StaticinjectOptionaloptions: InjectLambdaContextOptionsThis method is deprecated and will be removed in the future major versions. Use () instead.
StaticinjectOptionaloptions: InjectLambdaContextOptions
The Logger utility provides an opinionated logger with output structured as JSON for AWS Lambda.
Key features Capturing key fields from the Lambda context, cold starts, and structure logging output as JSON. Logging Lambda invocation events when instructed (disabled by default). Switch log level to
DEBUGfor a percentage of invocations (sampling). Buffering logs for a specific request or invocation, and flushing them automatically on error or manually as needed. Appending additional keys to structured logs at any point in time. Providing a custom log formatter (Bring Your Own Formatter) to output logs in a structure compatible with your organization’s Logging RFC.After initializing the Logger class, you can use the methods to log messages at different levels.
Example
To enrich the log items with information from the Lambda context, you can use the
addContext()method.Example
You can also add additional attributes to all log items using the
appendKeys()method.Example
If you write your functions as classes and use TypeScript, you can use the
injectLambdaContext()class method decorator to automatically add context to your logs and clear the state after the invocation.If instead you use Middy.js middlewares, you use the
injectLambdaContext()middleware.See
https://docs.aws.amazon.com/powertools/typescript/latest/core/logger/