Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@aws-lambda-powertools/logger

Package Overview
Dependencies
Maintainers
0
Versions
96
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aws-lambda-powertools/logger - npm Package Compare versions

Comparing version 2.2.0 to 2.3.0

54

lib/cjs/Logger.d.ts

@@ -147,2 +147,6 @@ import { Utility } from '@aws-lambda-powertools/commons';

/**
* Temporary log attributes that can be appended with `appendKeys()` method.
*/
private temporaryLogAttributes;
/**
* Log level used by the current instance of Logger.

@@ -169,10 +173,12 @@ *

/**
* It adds the given attributes (key-value pairs) to all log items generated by this Logger instance.
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes
* @returns {void}
*/
addPersistentLogAttributes(attributes?: LogAttributes): void;
addPersistentLogAttributes(attributes: LogAttributes): void;
/**
* Alias for addPersistentLogAttributes.
* It adds the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.
*

@@ -182,4 +188,10 @@ * @param {LogAttributes} attributes

*/
appendKeys(attributes?: LogAttributes): void;
appendKeys(attributes: LogAttributes): void;
/**
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @param attributes - The attributes to add to all log items.
*/
appendPersistentKeys(attributes: LogAttributes): void;
/**
* It creates a separate Logger instance, identical to the current one

@@ -280,3 +292,6 @@ * It's possible to overwrite the new instance options by passing them.

injectLambdaContext(options?: InjectLambdaContextOptions): HandlerMethodDecorator;
static injectLambdaContextAfterOrOnError(logger: Logger, initialPersistentAttributes: LogAttributes, options?: InjectLambdaContextOptions): void;
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link resetKeys()} instead.
*/
static injectLambdaContextAfterOrOnError(logger: Logger, _persistentAttributes: LogAttributes, options?: InjectLambdaContextOptions): void;
static injectLambdaContextBefore(logger: Logger, event: unknown, context: Context, options?: InjectLambdaContextOptions): void;

@@ -300,3 +315,3 @@ /**

/**
* Alias for removePersistentLogAttributes.
* It removes temporary attributes based on provided keys to all log items generated by this Logger instance.
*

@@ -308,4 +323,23 @@ * @param {string[]} keys

/**
* It removes attributes based on provided keys to all log items generated by this Logger instance.
* Remove the given keys from the persistent keys.
*
* @example
* ```typescript
* import { Logger } from '@aws-lambda-powertools/logger';
*
* const logger = new Logger({
* persistentKeys: {
* environment: 'prod',
* },
* });
*
* logger.removePersistentKeys(['environment']);
* ```
*
* @param keys - The keys to remove from the persistent attributes.
*/
removePersistentKeys(keys: string[]): void;
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link removePersistentKeys()} instead.
*
* @param {string[]} keys

@@ -316,2 +350,6 @@ * @returns {void}

/**
* It removes all temporary log attributes added with `appendKeys()` method.
*/
resetKeys(): void;
/**
* Set the log level for this Logger instance.

@@ -329,2 +367,4 @@ *

*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes

@@ -331,0 +371,0 @@ * @returns {void}

@@ -16,3 +16,3 @@ "use strict";

};
var _Logger_buffer, _Logger_isInitialized;
var _Logger_buffer, _Logger_isInitialized, _Logger_keys, _Logger_initialLogLevel;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -169,2 +169,6 @@ exports.Logger = void 0;

/**
* Temporary log attributes that can be appended with `appendKeys()` method.
*/
this.temporaryLogAttributes = {};
/**
* Buffer used to store logs until the logger is initialized.

@@ -180,2 +184,15 @@ *

_Logger_isInitialized.set(this, false);
/**
* Map used to hold the list of keys and their type.
*
* Because keys of different types can be overwritten, we keep a list of keys that were added and their last
* type. We then use this map at log preparation time to pick the last one.
*/
_Logger_keys.set(this, new Map());
/**
* This is the initial log leval as set during the initialization of the logger.
*
* We keep this value to be able to reset the log level to the initial value when the sample rate is refreshed.
*/
_Logger_initialLogLevel.set(this, 12);
const { customConfigService, ...rest } = options;

@@ -212,4 +229,6 @@ this.setCustomConfigService(customConfigService);

/**
* It adds the given attributes (key-value pairs) to all log items generated by this Logger instance.
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes

@@ -219,6 +238,6 @@ * @returns {void}

addPersistentLogAttributes(attributes) {
(0, lodash_merge_1.default)(this.persistentLogAttributes, attributes);
this.appendPersistentKeys(attributes);
}
/**
* Alias for addPersistentLogAttributes.
* It adds the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.
*

@@ -229,5 +248,19 @@ * @param {LogAttributes} attributes

appendKeys(attributes) {
this.addPersistentLogAttributes(attributes);
for (const attributeKey of Object.keys(attributes)) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(attributeKey, 'temp');
}
(0, lodash_merge_1.default)(this.temporaryLogAttributes, attributes);
}
/**
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @param attributes - The attributes to add to all log items.
*/
appendPersistentKeys(attributes) {
for (const attributeKey of Object.keys(attributes)) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(attributeKey, 'persistent');
}
(0, lodash_merge_1.default)(this.persistentLogAttributes, attributes);
}
/**
* It creates a separate Logger instance, identical to the current one

@@ -251,2 +284,3 @@ * It's possible to overwrite the new instance options by passing them.

persistentLogAttributes: this.persistentLogAttributes,
temporaryLogAttributes: this.temporaryLogAttributes,
}, options));

@@ -370,8 +404,2 @@ if (this.powertoolsLogData.lambdaContext)

descriptor.value = async function (event, context, callback) {
let initialPersistentAttributes = {};
if (options && options.clearState === true) {
initialPersistentAttributes = {
...loggerRef.getPersistentLogAttributes(),
};
}
Logger.injectLambdaContextBefore(loggerRef, event, context, options);

@@ -386,3 +414,4 @@ let result;

finally {
Logger.injectLambdaContextAfterOrOnError(loggerRef, initialPersistentAttributes, options);
if (options?.clearState || options?.resetKeys)
loggerRef.resetKeys();
}

@@ -393,5 +422,9 @@ return result;

}
static injectLambdaContextAfterOrOnError(logger, initialPersistentAttributes, options) {
if (options && options.clearState === true) {
logger.setPersistentLogAttributes(initialPersistentAttributes);
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link resetKeys()} instead.
*/
/* istanbul ignore next */
static injectLambdaContextAfterOrOnError(logger, _persistentAttributes, options) {
if (options && (options.clearState || options?.resetKeys)) {
logger.resetKeys();
}

@@ -430,3 +463,3 @@ }

/**
* Alias for removePersistentLogAttributes.
* It removes temporary attributes based on provided keys to all log items generated by this Logger instance.
*

@@ -437,7 +470,44 @@ * @param {string[]} keys

removeKeys(keys) {
this.removePersistentLogAttributes(keys);
for (const key of keys) {
this.temporaryLogAttributes[key] = undefined;
if (this.persistentLogAttributes[key]) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(key, 'persistent');
}
else {
__classPrivateFieldGet(this, _Logger_keys, "f").delete(key);
}
}
}
/**
* It removes attributes based on provided keys to all log items generated by this Logger instance.
* Remove the given keys from the persistent keys.
*
* @example
* ```typescript
* import { Logger } from '@aws-lambda-powertools/logger';
*
* const logger = new Logger({
* persistentKeys: {
* environment: 'prod',
* },
* });
*
* logger.removePersistentKeys(['environment']);
* ```
*
* @param keys - The keys to remove from the persistent attributes.
*/
removePersistentKeys(keys) {
for (const key of keys) {
this.persistentLogAttributes[key] = undefined;
if (this.temporaryLogAttributes[key]) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(key, 'temp');
}
else {
__classPrivateFieldGet(this, _Logger_keys, "f").delete(key);
}
}
}
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link removePersistentKeys()} instead.
*
* @param {string[]} keys

@@ -447,7 +517,17 @@ * @returns {void}

removePersistentLogAttributes(keys) {
for (const key of keys) {
if (this.persistentLogAttributes && key in this.persistentLogAttributes) {
delete this.persistentLogAttributes[key];
this.removePersistentKeys(keys);
}
/**
* It removes all temporary log attributes added with `appendKeys()` method.
*/
resetKeys() {
for (const key of Object.keys(this.temporaryLogAttributes)) {
if (this.persistentLogAttributes[key]) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(key, 'persistent');
}
else {
__classPrivateFieldGet(this, _Logger_keys, "f").delete(key);
}
}
this.temporaryLogAttributes = {};
}

@@ -476,2 +556,4 @@ /**

*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes

@@ -586,6 +668,14 @@ * @returns {void}

};
// gradually merge additional attributes starting from customer-provided persistent attributes
let additionalLogAttributes = { ...this.getPersistentLogAttributes() };
const additionalAttributes = {};
// gradually add additional attributes picking only the last added for each key
for (const [key, type] of __classPrivateFieldGet(this, _Logger_keys, "f")) {
if (type === 'persistent') {
additionalAttributes[key] = this.persistentLogAttributes[key];
}
else {
additionalAttributes[key] = this.temporaryLogAttributes[key];
}
}
// if the main input is not a string, then it's an object with additional attributes, so we merge it
additionalLogAttributes = (0, lodash_merge_1.default)(additionalLogAttributes, otherInput);
(0, lodash_merge_1.default)(additionalAttributes, otherInput);
// then we merge the extra input attributes (if any)

@@ -598,5 +688,5 @@ for (const item of extraInput) {

: item;
additionalLogAttributes = (0, lodash_merge_1.default)(additionalLogAttributes, attributes);
(0, lodash_merge_1.default)(additionalAttributes, attributes);
}
return this.getLogFormatter().formatAttributes(unformattedBaseAttributes, additionalLogAttributes);
return this.getLogFormatter().formatAttributes(unformattedBaseAttributes, additionalAttributes);
}

@@ -790,2 +880,3 @@ /**

this.logLevel = this.logLevelThresholds[constructorLogLevel];
__classPrivateFieldSet(this, _Logger_initialLogLevel, this.logLevel, "f");
return;

@@ -798,2 +889,3 @@ }

this.logLevel = this.logLevelThresholds[customConfigValue];
__classPrivateFieldSet(this, _Logger_initialLogLevel, this.logLevel, "f");
return;

@@ -804,2 +896,3 @@ }

this.logLevel = this.logLevelThresholds[envVarsValue];
__classPrivateFieldSet(this, _Logger_initialLogLevel, this.logLevel, "f");
return;

@@ -831,2 +924,5 @@ }

}
else {
this.setLogLevel(this.getLogLevelNameFromNumber(__classPrivateFieldGet(this, _Logger_initialLogLevel, "f")));
}
return;

@@ -881,6 +977,9 @@ }

setOptions(options) {
const { logLevel, serviceName, sampleRateValue, logFormatter, persistentLogAttributes, environment, } = options;
const { logLevel, serviceName, sampleRateValue, logFormatter, persistentKeys, persistentLogAttributes, // deprecated in favor of persistentKeys
environment, } = options;
if (persistentLogAttributes && persistentKeys) {
this.warn('Both persistentLogAttributes and persistentKeys options were provided. Using persistentKeys as persistentLogAttributes is deprecated and will be removed in future releases');
}
// configurations that affect log content
this.setPowertoolsLogData(serviceName, environment);
this.addPersistentLogAttributes(persistentLogAttributes);
this.setPowertoolsLogData(serviceName, environment, persistentKeys || persistentLogAttributes);
// configurations that affect Logger behavior

@@ -916,6 +1015,6 @@ this.setLogEvent();

});
this.addPersistentLogAttributes(persistentLogAttributes);
this.appendPersistentKeys(persistentLogAttributes);
}
}
exports.Logger = Logger;
_Logger_buffer = new WeakMap(), _Logger_isInitialized = new WeakMap();
_Logger_buffer = new WeakMap(), _Logger_isInitialized = new WeakMap(), _Logger_keys = new WeakMap(), _Logger_initialLogLevel = new WeakMap();

16

lib/cjs/middleware/middy.js

@@ -33,4 +33,3 @@ "use strict";

const loggers = target instanceof Array ? target : [target];
const persistentAttributes = [];
const isClearState = options && options.clearState === true;
const isResetStateEnabled = options && (options.clearState || options.resetKeys);
/**

@@ -48,7 +47,4 @@ * Set the cleanup function to be called in case other middlewares return early.

const injectLambdaContextBefore = async (request) => {
loggers.forEach((logger, index) => {
if (isClearState) {
persistentAttributes[index] = {
...logger.getPersistentLogAttributes(),
};
loggers.forEach((logger) => {
if (isResetStateEnabled) {
setCleanupFunction(request);

@@ -60,5 +56,5 @@ }

const injectLambdaContextAfterOrOnError = async () => {
if (isClearState) {
loggers.forEach((logger, index) => {
Logger_js_1.Logger.injectLambdaContextAfterOrOnError(logger, persistentAttributes[index], options);
if (isResetStateEnabled) {
loggers.forEach((logger) => {
logger.resetKeys();
});

@@ -65,0 +61,0 @@ }

@@ -10,5 +10,12 @@ import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';

logEvent?: boolean;
/**
* @deprecated Use `resetKeys` instead.
*/
clearState?: boolean;
/**
* If `true`, the logger will reset the keys added via {@link `appendKeys()`}
*/
resetKeys?: boolean;
};
type ConstructorOptions = {
type BaseConstructorOptions = {
logLevel?: LogLevel;

@@ -19,5 +26,37 @@ serviceName?: string;

customConfigService?: ConfigServiceInterface;
persistentLogAttributes?: LogAttributes;
environment?: Environment;
};
type PersistentKeysOption = {
/**
* Keys that will be added in all log items.
*/
persistentKeys?: LogAttributes;
/**
* @deprecated Use `persistentKeys` instead.
*/
persistentLogAttributes?: never;
};
type DeprecatedOption = {
/**
* @deprecated Use `persistentKeys` instead.
*/
persistentLogAttributes?: LogAttributes;
/**
* Keys that will be added in all log items.
*/
persistentKeys?: never;
};
/**
* Options for the Logger class constructor.
*
* @type {Object} ConstructorOptions
* @property {LogLevel} [logLevel] - The log level.
* @property {string} [serviceName] - The service name.
* @property {number} [sampleRateValue] - The sample rate value.
* @property {LogFormatterInterface} [logFormatter] - The custom log formatter.
* @property {ConfigServiceInterface} [customConfigService] - The custom config service.
* @property {Environment} [environment] - The environment.
* @property {LogAttributes} [persistentKeys] - Keys that will be added in all log items.
*/
type ConstructorOptions = BaseConstructorOptions & (PersistentKeysOption | DeprecatedOption);
type LambdaFunctionContext = Pick<Context, 'functionName' | 'memoryLimitInMB' | 'functionVersion' | 'invokedFunctionArn' | 'awsRequestId'> & {

@@ -24,0 +63,0 @@ coldStart: boolean;

@@ -147,2 +147,6 @@ import { Utility } from '@aws-lambda-powertools/commons';

/**
* Temporary log attributes that can be appended with `appendKeys()` method.
*/
private temporaryLogAttributes;
/**
* Log level used by the current instance of Logger.

@@ -169,10 +173,12 @@ *

/**
* It adds the given attributes (key-value pairs) to all log items generated by this Logger instance.
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes
* @returns {void}
*/
addPersistentLogAttributes(attributes?: LogAttributes): void;
addPersistentLogAttributes(attributes: LogAttributes): void;
/**
* Alias for addPersistentLogAttributes.
* It adds the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.
*

@@ -182,4 +188,10 @@ * @param {LogAttributes} attributes

*/
appendKeys(attributes?: LogAttributes): void;
appendKeys(attributes: LogAttributes): void;
/**
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @param attributes - The attributes to add to all log items.
*/
appendPersistentKeys(attributes: LogAttributes): void;
/**
* It creates a separate Logger instance, identical to the current one

@@ -280,3 +292,6 @@ * It's possible to overwrite the new instance options by passing them.

injectLambdaContext(options?: InjectLambdaContextOptions): HandlerMethodDecorator;
static injectLambdaContextAfterOrOnError(logger: Logger, initialPersistentAttributes: LogAttributes, options?: InjectLambdaContextOptions): void;
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link resetKeys()} instead.
*/
static injectLambdaContextAfterOrOnError(logger: Logger, _persistentAttributes: LogAttributes, options?: InjectLambdaContextOptions): void;
static injectLambdaContextBefore(logger: Logger, event: unknown, context: Context, options?: InjectLambdaContextOptions): void;

@@ -300,3 +315,3 @@ /**

/**
* Alias for removePersistentLogAttributes.
* It removes temporary attributes based on provided keys to all log items generated by this Logger instance.
*

@@ -308,4 +323,23 @@ * @param {string[]} keys

/**
* It removes attributes based on provided keys to all log items generated by this Logger instance.
* Remove the given keys from the persistent keys.
*
* @example
* ```typescript
* import { Logger } from '@aws-lambda-powertools/logger';
*
* const logger = new Logger({
* persistentKeys: {
* environment: 'prod',
* },
* });
*
* logger.removePersistentKeys(['environment']);
* ```
*
* @param keys - The keys to remove from the persistent attributes.
*/
removePersistentKeys(keys: string[]): void;
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link removePersistentKeys()} instead.
*
* @param {string[]} keys

@@ -316,2 +350,6 @@ * @returns {void}

/**
* It removes all temporary log attributes added with `appendKeys()` method.
*/
resetKeys(): void;
/**
* Set the log level for this Logger instance.

@@ -329,2 +367,4 @@ *

*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes

@@ -331,0 +371,0 @@ * @returns {void}

@@ -12,3 +12,3 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {

};
var _Logger_buffer, _Logger_isInitialized;
var _Logger_buffer, _Logger_isInitialized, _Logger_keys, _Logger_initialLogLevel;
import { Utility } from '@aws-lambda-powertools/commons';

@@ -163,2 +163,6 @@ import merge from 'lodash.merge';

/**
* Temporary log attributes that can be appended with `appendKeys()` method.
*/
this.temporaryLogAttributes = {};
/**
* Buffer used to store logs until the logger is initialized.

@@ -174,2 +178,15 @@ *

_Logger_isInitialized.set(this, false);
/**
* Map used to hold the list of keys and their type.
*
* Because keys of different types can be overwritten, we keep a list of keys that were added and their last
* type. We then use this map at log preparation time to pick the last one.
*/
_Logger_keys.set(this, new Map());
/**
* This is the initial log leval as set during the initialization of the logger.
*
* We keep this value to be able to reset the log level to the initial value when the sample rate is refreshed.
*/
_Logger_initialLogLevel.set(this, 12);
const { customConfigService, ...rest } = options;

@@ -206,4 +223,6 @@ this.setCustomConfigService(customConfigService);

/**
* It adds the given attributes (key-value pairs) to all log items generated by this Logger instance.
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes

@@ -213,6 +232,6 @@ * @returns {void}

addPersistentLogAttributes(attributes) {
merge(this.persistentLogAttributes, attributes);
this.appendPersistentKeys(attributes);
}
/**
* Alias for addPersistentLogAttributes.
* It adds the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.
*

@@ -223,5 +242,19 @@ * @param {LogAttributes} attributes

appendKeys(attributes) {
this.addPersistentLogAttributes(attributes);
for (const attributeKey of Object.keys(attributes)) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(attributeKey, 'temp');
}
merge(this.temporaryLogAttributes, attributes);
}
/**
* It adds the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @param attributes - The attributes to add to all log items.
*/
appendPersistentKeys(attributes) {
for (const attributeKey of Object.keys(attributes)) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(attributeKey, 'persistent');
}
merge(this.persistentLogAttributes, attributes);
}
/**
* It creates a separate Logger instance, identical to the current one

@@ -245,2 +278,3 @@ * It's possible to overwrite the new instance options by passing them.

persistentLogAttributes: this.persistentLogAttributes,
temporaryLogAttributes: this.temporaryLogAttributes,
}, options));

@@ -364,8 +398,2 @@ if (this.powertoolsLogData.lambdaContext)

descriptor.value = async function (event, context, callback) {
let initialPersistentAttributes = {};
if (options && options.clearState === true) {
initialPersistentAttributes = {
...loggerRef.getPersistentLogAttributes(),
};
}
Logger.injectLambdaContextBefore(loggerRef, event, context, options);

@@ -380,3 +408,4 @@ let result;

finally {
Logger.injectLambdaContextAfterOrOnError(loggerRef, initialPersistentAttributes, options);
if (options?.clearState || options?.resetKeys)
loggerRef.resetKeys();
}

@@ -387,5 +416,9 @@ return result;

}
static injectLambdaContextAfterOrOnError(logger, initialPersistentAttributes, options) {
if (options && options.clearState === true) {
logger.setPersistentLogAttributes(initialPersistentAttributes);
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link resetKeys()} instead.
*/
/* istanbul ignore next */
static injectLambdaContextAfterOrOnError(logger, _persistentAttributes, options) {
if (options && (options.clearState || options?.resetKeys)) {
logger.resetKeys();
}

@@ -424,3 +457,3 @@ }

/**
* Alias for removePersistentLogAttributes.
* It removes temporary attributes based on provided keys to all log items generated by this Logger instance.
*

@@ -431,7 +464,44 @@ * @param {string[]} keys

removeKeys(keys) {
this.removePersistentLogAttributes(keys);
for (const key of keys) {
this.temporaryLogAttributes[key] = undefined;
if (this.persistentLogAttributes[key]) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(key, 'persistent');
}
else {
__classPrivateFieldGet(this, _Logger_keys, "f").delete(key);
}
}
}
/**
* It removes attributes based on provided keys to all log items generated by this Logger instance.
* Remove the given keys from the persistent keys.
*
* @example
* ```typescript
* import { Logger } from '@aws-lambda-powertools/logger';
*
* const logger = new Logger({
* persistentKeys: {
* environment: 'prod',
* },
* });
*
* logger.removePersistentKeys(['environment']);
* ```
*
* @param keys - The keys to remove from the persistent attributes.
*/
removePersistentKeys(keys) {
for (const key of keys) {
this.persistentLogAttributes[key] = undefined;
if (this.temporaryLogAttributes[key]) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(key, 'temp');
}
else {
__classPrivateFieldGet(this, _Logger_keys, "f").delete(key);
}
}
}
/**
* @deprecated This method is deprecated and will be removed in the future major versions. Use {@link removePersistentKeys()} instead.
*
* @param {string[]} keys

@@ -441,7 +511,17 @@ * @returns {void}

removePersistentLogAttributes(keys) {
for (const key of keys) {
if (this.persistentLogAttributes && key in this.persistentLogAttributes) {
delete this.persistentLogAttributes[key];
this.removePersistentKeys(keys);
}
/**
* It removes all temporary log attributes added with `appendKeys()` method.
*/
resetKeys() {
for (const key of Object.keys(this.temporaryLogAttributes)) {
if (this.persistentLogAttributes[key]) {
__classPrivateFieldGet(this, _Logger_keys, "f").set(key, 'persistent');
}
else {
__classPrivateFieldGet(this, _Logger_keys, "f").delete(key);
}
}
this.temporaryLogAttributes = {};
}

@@ -470,2 +550,4 @@ /**

*
* @deprecated This method is deprecated and will be removed in the future major versions, please use {@link appendPersistentKeys()} instead.
*
* @param {LogAttributes} attributes

@@ -580,6 +662,14 @@ * @returns {void}

};
// gradually merge additional attributes starting from customer-provided persistent attributes
let additionalLogAttributes = { ...this.getPersistentLogAttributes() };
const additionalAttributes = {};
// gradually add additional attributes picking only the last added for each key
for (const [key, type] of __classPrivateFieldGet(this, _Logger_keys, "f")) {
if (type === 'persistent') {
additionalAttributes[key] = this.persistentLogAttributes[key];
}
else {
additionalAttributes[key] = this.temporaryLogAttributes[key];
}
}
// if the main input is not a string, then it's an object with additional attributes, so we merge it
additionalLogAttributes = merge(additionalLogAttributes, otherInput);
merge(additionalAttributes, otherInput);
// then we merge the extra input attributes (if any)

@@ -592,5 +682,5 @@ for (const item of extraInput) {

: item;
additionalLogAttributes = merge(additionalLogAttributes, attributes);
merge(additionalAttributes, attributes);
}
return this.getLogFormatter().formatAttributes(unformattedBaseAttributes, additionalLogAttributes);
return this.getLogFormatter().formatAttributes(unformattedBaseAttributes, additionalAttributes);
}

@@ -784,2 +874,3 @@ /**

this.logLevel = this.logLevelThresholds[constructorLogLevel];
__classPrivateFieldSet(this, _Logger_initialLogLevel, this.logLevel, "f");
return;

@@ -792,2 +883,3 @@ }

this.logLevel = this.logLevelThresholds[customConfigValue];
__classPrivateFieldSet(this, _Logger_initialLogLevel, this.logLevel, "f");
return;

@@ -798,2 +890,3 @@ }

this.logLevel = this.logLevelThresholds[envVarsValue];
__classPrivateFieldSet(this, _Logger_initialLogLevel, this.logLevel, "f");
return;

@@ -825,2 +918,5 @@ }

}
else {
this.setLogLevel(this.getLogLevelNameFromNumber(__classPrivateFieldGet(this, _Logger_initialLogLevel, "f")));
}
return;

@@ -875,6 +971,9 @@ }

setOptions(options) {
const { logLevel, serviceName, sampleRateValue, logFormatter, persistentLogAttributes, environment, } = options;
const { logLevel, serviceName, sampleRateValue, logFormatter, persistentKeys, persistentLogAttributes, // deprecated in favor of persistentKeys
environment, } = options;
if (persistentLogAttributes && persistentKeys) {
this.warn('Both persistentLogAttributes and persistentKeys options were provided. Using persistentKeys as persistentLogAttributes is deprecated and will be removed in future releases');
}
// configurations that affect log content
this.setPowertoolsLogData(serviceName, environment);
this.addPersistentLogAttributes(persistentLogAttributes);
this.setPowertoolsLogData(serviceName, environment, persistentKeys || persistentLogAttributes);
// configurations that affect Logger behavior

@@ -910,6 +1009,6 @@ this.setLogEvent();

});
this.addPersistentLogAttributes(persistentLogAttributes);
this.appendPersistentKeys(persistentLogAttributes);
}
}
_Logger_buffer = new WeakMap(), _Logger_isInitialized = new WeakMap();
_Logger_buffer = new WeakMap(), _Logger_isInitialized = new WeakMap(), _Logger_keys = new WeakMap(), _Logger_initialLogLevel = new WeakMap();
export { Logger };

@@ -30,4 +30,3 @@ import { Logger } from '../Logger.js';

const loggers = target instanceof Array ? target : [target];
const persistentAttributes = [];
const isClearState = options && options.clearState === true;
const isResetStateEnabled = options && (options.clearState || options.resetKeys);
/**

@@ -45,7 +44,4 @@ * Set the cleanup function to be called in case other middlewares return early.

const injectLambdaContextBefore = async (request) => {
loggers.forEach((logger, index) => {
if (isClearState) {
persistentAttributes[index] = {
...logger.getPersistentLogAttributes(),
};
loggers.forEach((logger) => {
if (isResetStateEnabled) {
setCleanupFunction(request);

@@ -57,5 +53,5 @@ }

const injectLambdaContextAfterOrOnError = async () => {
if (isClearState) {
loggers.forEach((logger, index) => {
Logger.injectLambdaContextAfterOrOnError(logger, persistentAttributes[index], options);
if (isResetStateEnabled) {
loggers.forEach((logger) => {
logger.resetKeys();
});

@@ -62,0 +58,0 @@ }

@@ -10,5 +10,12 @@ import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';

logEvent?: boolean;
/**
* @deprecated Use `resetKeys` instead.
*/
clearState?: boolean;
/**
* If `true`, the logger will reset the keys added via {@link `appendKeys()`}
*/
resetKeys?: boolean;
};
type ConstructorOptions = {
type BaseConstructorOptions = {
logLevel?: LogLevel;

@@ -19,5 +26,37 @@ serviceName?: string;

customConfigService?: ConfigServiceInterface;
persistentLogAttributes?: LogAttributes;
environment?: Environment;
};
type PersistentKeysOption = {
/**
* Keys that will be added in all log items.
*/
persistentKeys?: LogAttributes;
/**
* @deprecated Use `persistentKeys` instead.
*/
persistentLogAttributes?: never;
};
type DeprecatedOption = {
/**
* @deprecated Use `persistentKeys` instead.
*/
persistentLogAttributes?: LogAttributes;
/**
* Keys that will be added in all log items.
*/
persistentKeys?: never;
};
/**
* Options for the Logger class constructor.
*
* @type {Object} ConstructorOptions
* @property {LogLevel} [logLevel] - The log level.
* @property {string} [serviceName] - The service name.
* @property {number} [sampleRateValue] - The sample rate value.
* @property {LogFormatterInterface} [logFormatter] - The custom log formatter.
* @property {ConfigServiceInterface} [customConfigService] - The custom config service.
* @property {Environment} [environment] - The environment.
* @property {LogAttributes} [persistentKeys] - Keys that will be added in all log items.
*/
type ConstructorOptions = BaseConstructorOptions & (PersistentKeysOption | DeprecatedOption);
type LambdaFunctionContext = Pick<Context, 'functionName' | 'memoryLimitInMB' | 'functionVersion' | 'invokedFunctionArn' | 'awsRequestId'> & {

@@ -24,0 +63,0 @@ coldStart: boolean;

{
"name": "@aws-lambda-powertools/logger",
"version": "2.2.0",
"version": "2.3.0",
"description": "The logging package for the Powertools for AWS Lambda (TypeScript) library",

@@ -28,3 +28,3 @@ "author": {

"dependencies": {
"@aws-lambda-powertools/commons": "^2.2.0",
"@aws-lambda-powertools/commons": "^2.3.0",
"lodash.merge": "^4.6.2"

@@ -31,0 +31,0 @@ },

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc