Skip to content

feat(logger): add clearState() method #2408

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 63 additions & 26 deletions packages/logger/src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ class Logger extends Utility implements LoggerInterface {
* Sometimes we need to log warnings before the logger is fully initialized, however we can't log them
* immediately because the logger is not ready yet. This buffer stores those logs until the logger is ready.
*/
/**
* Temporary log attributes that can be appended with `appendKeys()` method.
*/
private temporaryLogAttributes: LogAttributes = {};
#buffer: [number, Parameters<Logger['createAndPopulateLogItem']>][] = [];
/**
* Flag used to determine if the logger is initialized.
Expand Down Expand Up @@ -234,7 +238,7 @@ class Logger extends Utility implements LoggerInterface {
}

/**
* 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.
*
* @param {LogAttributes} attributes
* @returns {void}
Expand All @@ -244,13 +248,22 @@ class Logger extends Utility implements LoggerInterface {
}

/**
* Alias for addPersistentLogAttributes.
* Alias for addTemporaryLogAttributes.
*
* @param {LogAttributes} attributes
* @returns {void}
*/
public appendKeys(attributes?: LogAttributes): void {
this.addPersistentLogAttributes(attributes);
merge(this.temporaryLogAttributes, attributes);
}

/**
* It clears temporary log attributes.
*
* @returns {void}
*/
public clearState(): void {
this.temporaryLogAttributes = {};
}

/**
Expand All @@ -274,6 +287,7 @@ class Logger extends Utility implements LoggerInterface {
customConfigService: this.getCustomConfigService(),
environment: this.powertoolsLogData.environment,
persistentLogAttributes: this.persistentLogAttributes,
temporaryLogAttributes: this.temporaryLogAttributes,
},
options
)
Expand Down Expand Up @@ -354,6 +368,16 @@ class Logger extends Utility implements LoggerInterface {
return this.persistentLogAttributes;
}

/**
* It returns the temporary log attributes, added with `appendKeys()` method.
*
* @private
* @returns {LogAttributes}
*/
public getTemporaryLogAttributes(): LogAttributes {
return this.temporaryLogAttributes;
}

/**
* It prints a log item with level INFO.
*
Expand Down Expand Up @@ -417,13 +441,6 @@ class Logger extends Utility implements LoggerInterface {
context,
callback
) {
let initialPersistentAttributes = {};
if (options && options.clearState === true) {
initialPersistentAttributes = {
...loggerRef.getPersistentLogAttributes(),
};
}

Logger.injectLambdaContextBefore(loggerRef, event, context, options);

let result: unknown;
Expand All @@ -434,7 +451,7 @@ class Logger extends Utility implements LoggerInterface {
} finally {
Logger.injectLambdaContextAfterOrOnError(
loggerRef,
initialPersistentAttributes,
loggerRef.getPersistentLogAttributes(),
options
);
}
Expand All @@ -446,11 +463,12 @@ class Logger extends Utility implements LoggerInterface {

public static injectLambdaContextAfterOrOnError(
logger: Logger,
initialPersistentAttributes: LogAttributes,
persistentAttributes: LogAttributes,
options?: InjectLambdaContextOptions
): void {
if (options && options.clearState === true) {
logger.setPersistentLogAttributes(initialPersistentAttributes);
logger.clearState();
logger.addPersistentLogAttributes(persistentAttributes);
}
}

Expand Down Expand Up @@ -493,27 +511,31 @@ class Logger extends Utility implements LoggerInterface {
}

/**
* Alias for removePersistentLogAttributes.
* It removes attributes based on provided keys to all log items generated by this Logger instance.
*
* @param {string[]} keys
* @returns {void}
*/
public removeKeys(keys: string[]): void {
this.removePersistentLogAttributes(keys);
const removeKey = (attributes: LogAttributes, key: string): void => {
if (attributes && key in attributes) {
delete attributes[key];
}
};
for (const key of keys) {
removeKey(this.persistentLogAttributes, key);
removeKey(this.temporaryLogAttributes, key);
}
}

/**
* It removes attributes based on provided keys to all log items generated by this Logger instance.
* Alias for removeKeys().
*
* @param {string[]} keys
* @returns {void}
*/
public removePersistentLogAttributes(keys: string[]): void {
for (const key of keys) {
if (this.persistentLogAttributes && key in this.persistentLogAttributes) {
delete this.persistentLogAttributes[key];
}
}
this.removeKeys(keys);
}

/**
Expand All @@ -534,6 +556,8 @@ class Logger extends Utility implements LoggerInterface {
}

/**
* @deprecated This method is deprecated and will be removed in the future major versions.
*
* It sets the given attributes (key-value pairs) to all log items generated by this Logger instance.
* Note: this replaces the pre-existing value.
*
Expand Down Expand Up @@ -665,8 +689,11 @@ class Logger extends Utility implements LoggerInterface {
...this.getPowertoolsLogData(),
};

// gradually merge additional attributes starting from customer-provided persistent attributes
let additionalLogAttributes = { ...this.getPersistentLogAttributes() };
// gradually merge additional attributes starting from customer-provided persistent & temporary attributes
let additionalLogAttributes = {
...this.getPersistentLogAttributes(),
...this.getTemporaryLogAttributes(),
};
// if the main input is not a string, then it's an object with additional attributes, so we merge it
additionalLogAttributes = merge(additionalLogAttributes, otherInput);
// then we merge the extra input attributes (if any)
Expand Down Expand Up @@ -1023,13 +1050,23 @@ class Logger extends Utility implements LoggerInterface {
serviceName,
sampleRateValue,
logFormatter,
persistentLogAttributes,
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
this.setLogEvent();
Expand Down
16 changes: 3 additions & 13 deletions packages/logger/src/middleware/middy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Logger } from '../Logger.js';
import type { LogAttributes } from '../types/Log.js';
import type { InjectLambdaContextOptions } from '../types/Logger.js';
import { LOGGER_KEY } from '@aws-lambda-powertools/commons';
import type {
Expand Down Expand Up @@ -37,7 +36,6 @@ const injectLambdaContext = (
options?: InjectLambdaContextOptions
): MiddlewareLikeObj => {
const loggers = target instanceof Array ? target : [target];
const persistentAttributes: LogAttributes[] = [];
const isClearState = options && options.clearState === true;

/**
Expand All @@ -55,12 +53,8 @@ const injectLambdaContext = (
const injectLambdaContextBefore = async (
request: MiddyLikeRequest
): Promise<void> => {
loggers.forEach((logger: Logger, index: number) => {
loggers.forEach((logger: Logger) => {
if (isClearState) {
persistentAttributes[index] = {
...logger.getPersistentLogAttributes(),
};

setCleanupFunction(request);
}
Logger.injectLambdaContextBefore(
Expand All @@ -74,12 +68,8 @@ const injectLambdaContext = (

const injectLambdaContextAfterOrOnError = async (): Promise<void> => {
if (isClearState) {
loggers.forEach((logger: Logger, index: number) => {
Logger.injectLambdaContextAfterOrOnError(
logger,
persistentAttributes[index],
options
);
loggers.forEach((logger: Logger) => {
logger.clearState();
});
}
};
Expand Down
29 changes: 27 additions & 2 deletions packages/logger/src/types/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,41 @@ type InjectLambdaContextOptions = {
clearState?: boolean;
};

type ConstructorOptions = {
type BaseConstructorOptions = {
logLevel?: LogLevel;
serviceName?: string;
sampleRateValue?: number;
logFormatter?: LogFormatterInterface;
customConfigService?: ConfigServiceInterface;
persistentLogAttributes?: LogAttributes;
environment?: Environment;
};

type PersistentKeysOption = {
persistentKeys?: LogAttributes;
persistentLogAttributes?: never;
};

type DeprecatedOption = {
persistentLogAttributes?: LogAttributes;
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] - The keys that will be persisted in all log items.
* @property {LogAttributes} [persistentLogAttributes] - **Deprecated!** Use `persistentKeys`.
*/
type ConstructorOptions = BaseConstructorOptions &
(PersistentKeysOption | DeprecatedOption);

type LambdaFunctionContext = Pick<
Context,
| 'functionName'
Expand Down
Loading
Loading