Complete API documentation for @aws-lambda-powertools/logger.
constructor(options?: ConstructorOptions);Options:
logLevel?: LogLevel - Threshold for log output (default: 'INFO')serviceName?: string - Service identifier in logssampleRateValue?: number - 0-1 sampling rate for DEBUG logspersistentKeys?: LogAttributes - Attributes in all logs across invocationsenvironment?: string - Environment namelogFormatter?: LogFormatter - Custom log formatterlogRecordOrder?: string[] - Key ordering (mutually exclusive with logFormatter)jsonReplacerFn?: CustomJsonReplacerFn - Custom JSON serializationlogBufferOptions?: LogBufferOptions - Buffer configurationcorrelationIdSearchFn?: (event: unknown) => string - Custom correlation ID extractionExamples:
const logger = new Logger();
const logger = new Logger({ serviceName: 'orderService' });
const logger = new Logger({
serviceName: 'orderService',
logLevel: 'DEBUG',
persistentKeys: { version: '1.0.0' }
});trace(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
debug(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
info(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
warn(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
error(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
critical(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;Parameters:
input - String message OR object with message propertyextraInput - Error, string, or multiple attribute objectsExamples:
logger.info('Message');
logger.info('Message', { userId: '123' });
logger.error('Failed', error as Error);
logger.error('Failed', { customError: error as Error, orderId: '123' });
logger.info({ message: 'Created', orderId: '123', amount: 99.99 });addContext(context: Context): void;Adds Lambda execution context to all subsequent logs.
Adds:
function_name, function_arn, function_memory_sizefunction_request_id, cold_start, xray_trace_idExample:
export const handler = async (event, context) => {
logger.addContext(context);
logger.info('Processing'); // Includes Lambda context
};appendKeys(attributes: LogAttributes): void;
removeKeys(keys: string[]): void;
resetKeys(): void;Temporary attributes persist only during current invocation (until manually removed or resetKeys called).
Examples:
logger.appendKeys({ requestId: '123', userId: '456' });
logger.removeKeys(['requestId']);
logger.resetKeys(); // Clear all temporary keysappendPersistentKeys(attributes: LogAttributes): void;
removePersistentKeys(keys: string[]): void;
getPersistentLogAttributes(): LogAttributes;Persistent attributes remain across all invocations.
Examples:
logger.appendPersistentKeys({ version: '2.0.0', region: 'us-east-1' });
logger.removePersistentKeys(['version']);
const attrs = logger.getPersistentLogAttributes();setLogLevel(logLevel: LogLevel): void;
getLevelName(): Uppercase<LogLevel>;
get level(): number;Examples:
logger.setLogLevel('DEBUG');
const name = logger.getLevelName(); // 'DEBUG'
const level = logger.level; // 8Log Level Thresholds:
setCorrelationId(value: unknown, correlationIdPath?: string): void;
getCorrelationId(): unknown;Parameters:
value - Correlation ID value or event objectcorrelationIdPath - Optional JMESPath expression to extract from eventExamples:
import { correlationPaths } from '@aws-lambda-powertools/logger/correlationId';
logger.setCorrelationId(event, correlationPaths.API_GATEWAY_REST);
const id = logger.getCorrelationId();flushBuffer(): void;
clearBuffer(): void;Examples:
try {
await process();
logger.clearBuffer(); // Discard buffered logs
} catch (error) {
logger.flushBuffer(); // Output buffered logs for debugging
logger.error('Failed', error as Error);
}logEventIfEnabled(event: unknown, overwriteValue?: boolean): void;
getLogEvent(): boolean;
shouldLogEvent(overwriteValue?: boolean): boolean;Examples:
logger.logEventIfEnabled(event);
logger.logEventIfEnabled(event, true); // Force log
if (logger.getLogEvent()) {
// Event logging is enabled
}refreshSampleRateCalculation(): void;Recalculate debug sampling for warm Lambda starts.
Example:
export const handler = async (event, context) => {
logger.refreshSampleRateCalculation(); // Fresh calculation each invocation
logger.debug('Sampled'); // Logged based on sampleRateValue
};createChild(options?: ConstructorOptions): Logger;Creates child logger inheriting parent configuration.
Example:
const parent = new Logger({
serviceName: 'parent',
persistentKeys: { version: '1.0.0' }
});
const child = parent.createChild({
serviceName: 'child',
persistentKeys: { component: 'processor' }
});
child.info('Log'); // Includes both parent and child keysinjectLambdaContext(options?: InjectLambdaContextOptions): HandlerMethodDecorator;TypeScript decorator for automatic Lambda context injection.
Options:
logEvent?: boolean - Log event payload (default: false)resetKeys?: boolean - Clear temporary keys after invocation (default: false)flushBufferOnUncaughtError?: boolean - Flush buffer on errors (default: false)correlationIdPath?: string - JMESPath for correlation IDExample:
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
const logger = new Logger({ serviceName: 'myService' });
class Lambda implements LambdaInterface {
@logger.injectLambdaContext({ resetKeys: true })
public async handler(event: unknown, context: Context): Promise<void> {
logger.info('Processing'); // Context auto-injected
}
}
export const handler = new Lambda().handler.bind(new Lambda());import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware';
function injectLambdaContext(
target: Logger | Logger[],
options?: InjectLambdaContextOptions
): MiddlewareLikeObj;Parameters:
target - Logger instance or array of loggersoptions - Same as decorator optionsBehavior:
Examples:
import middy from '@middy/core';
const logger = new Logger({ serviceName: 'myService' });
const lambdaHandler = async (event, context) => {
logger.info('Processing');
return { statusCode: 200 };
};
// Single logger
export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));
// Multiple loggers
const mainLogger = new Logger({ serviceName: 'main' });
const auditLogger = new Logger({ serviceName: 'audit' });
export const handler = middy(lambdaHandler).use(
injectLambdaContext([mainLogger, auditLogger], { resetKeys: true })
);
// Full options
export const handler = middy(lambdaHandler).use(
injectLambdaContext(logger, {
logEvent: false,
resetKeys: true,
flushBufferOnUncaughtError: true,
correlationIdPath: correlationPaths.API_GATEWAY_REST
})
);import { correlationPaths, search } from '@aws-lambda-powertools/logger/correlationId';
const correlationPaths: {
API_GATEWAY_REST: string;
API_GATEWAY_HTTP: string;
APPSYNC_RESOLVER: string;
APPSYNC_AUTHORIZER: string;
APPLICATION_LOAD_BALANCER: string;
EVENT_BRIDGE: string;
LAMBDA_FUNCTION_URL: string;
S3_OBJECT_LAMBDA: string;
VPC_LATTICE: string;
};
function search(expression: string, data: unknown): unknown;Correlation Paths:
API_GATEWAY_REST: 'requestContext.requestId'API_GATEWAY_HTTP: 'requestContext.requestId'APPSYNC_RESOLVER: 'request.headers."x-amzn-trace-id"'APPSYNC_AUTHORIZER: 'requestContext.requestId'APPLICATION_LOAD_BALANCER: 'headers."x-amzn-trace-id"'EVENT_BRIDGE: 'id'LAMBDA_FUNCTION_URL: 'requestContext.requestId'S3_OBJECT_LAMBDA: 'xAmzRequestId'VPC_LATTICE: 'headers."x-amzn-trace-id"'Search Function:
Requires @aws-lambda-powertools/jmespath peer dependency.
const requestId = search(correlationPaths.API_GATEWAY_REST, event);
const custom = search('metadata.tracking.id', event);Usage Patterns:
// With setCorrelationId
logger.setCorrelationId(event, correlationPaths.API_GATEWAY_REST);
// With middleware
export const handler = middy(lambdaHandler).use(
injectLambdaContext(logger, {
correlationIdPath: correlationPaths.API_GATEWAY_REST
})
);
// With constructor
const logger = new Logger({
serviceName: 'myService',
correlationIdSearchFn: (event) => search(correlationPaths.API_GATEWAY_HTTP, event)
});
// Direct search
const id = search(correlationPaths.EVENT_BRIDGE, event);
logger.appendKeys({ correlationId: id });import { LogFormatter, LogItem } from '@aws-lambda-powertools/logger';
abstract class LogFormatter {
abstract formatAttributes(
attributes: UnformattedAttributes,
additionalLogAttributes: LogAttributes
): LogItem;
formatError(error: Error): LogAttributes;
formatTimestamp(now: Date): string;
getCodeLocation(stack?: string): string;
}
class LogItem {
constructor(params: { attributes: LogAttributes });
addAttributes(attributes: LogAttributes): this;
getAttributes(): LogAttributes;
setAttributes(attributes: LogAttributes): void;
prepareForPrint(): void;
removeEmptyKeys(attributes: LogAttributes): LogAttributes;
}Create Custom Formatter:
import type { UnformattedAttributes } from '@aws-lambda-powertools/logger/types';
class CustomFormatter extends LogFormatter {
public formatAttributes(
attributes: UnformattedAttributes,
additionalLogAttributes: LogAttributes
): LogItem {
return new LogItem({
attributes: {
'@timestamp': this.formatTimestamp(attributes.timestamp),
'level': attributes.logLevel,
'message': attributes.message,
'service': attributes.serviceName
}
}).addAttributes(additionalLogAttributes);
}
}
const logger = new Logger({
serviceName: 'myService',
logFormatter: new CustomFormatter()
});type LogLevel =
| 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'CRITICAL' | 'SILENT'
| 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'critical' | 'silent';
type LogAttributes = { [key: string]: unknown };
type LogItemMessage = string | (LogAttributes & { message: string });
type LogItemExtraInput = [Error | string] | LogAttributes[];
type ConstructorOptions = {
logLevel?: LogLevel;
serviceName?: string;
sampleRateValue?: number;
customConfigService?: ConfigServiceInterface;
environment?: string;
persistentKeys?: LogAttributes;
logFormatter?: LogFormatter;
logRecordOrder?: string[] | Set<string>;
jsonReplacerFn?: CustomJsonReplacerFn;
logBufferOptions?: LogBufferOptions;
correlationIdSearchFn?: (event: unknown) => string;
};
type LogBufferOptions = {
enabled?: boolean;
maxBytes?: number;
flushOnErrorLog?: boolean;
bufferAtVerbosity?: 'DEBUG' | 'INFO' | 'WARN' | 'debug' | 'info' | 'warn';
};
type InjectLambdaContextOptions = {
logEvent?: boolean;
resetKeys?: boolean;
flushBufferOnUncaughtError?: boolean;
correlationIdPath?: string;
};
type UnformattedAttributes = {
logLevel: string;
message: string;
timestamp: Date;
serviceName?: string;
sampleRateValue?: number;
xRayTraceId?: string;
lambdaContext?: {
functionName?: string;
memoryLimitInMB?: number;
invokedFunctionArn?: string;
awsRequestId?: string;
coldStart?: boolean;
};
error?: Error;
};
type CustomJsonReplacerFn = (key: string, value: unknown) => unknown;These methods are deprecated but still functional. Use the recommended alternatives.
// Deprecated - Use appendPersistentKeys()
addPersistentLogAttributes(attributes: LogAttributes): void;
setPersistentLogAttributes(attributes: LogAttributes): void;
// Deprecated - Use removePersistentKeys()
removePersistentLogAttributes(keys: string[]): void;
// Deprecated - Use getPersistentLogAttributes()
get persistentLogAttributes(): LogAttributes;InjectLambdaContextOptions:
clearState?: boolean; // Deprecated - Use resetKeys instead