Skip to content
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

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

Merged
merged 15 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
94 changes: 78 additions & 16 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 = {};
shdq marked this conversation as resolved.
Show resolved Hide resolved
#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,32 @@ class Logger extends Utility implements LoggerInterface {
}

/**
* Alias for addPersistentLogAttributes.
* It adds the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @param {LogAttributes} attributes
* @returns {void}
*/
public addTemporaryLogAttributes(attributes?: LogAttributes): void {
shdq marked this conversation as resolved.
Show resolved Hide resolved
merge(this.temporaryLogAttributes, attributes);
}

/**
* Alias for addTemporaryLogAttributes.
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
*
* @param {LogAttributes} attributes
* @returns {void}
*/
public appendKeys(attributes?: LogAttributes): void {
this.addPersistentLogAttributes(attributes);
this.addTemporaryLogAttributes(attributes);
}

/**
* It clears temporary log attributes.
*
* @returns {void}
*/
public clearState(): void {
shdq marked this conversation as resolved.
Show resolved Hide resolved
this.temporaryLogAttributes = {};
}

/**
Expand All @@ -274,6 +297,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 +378,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 {
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
return this.temporaryLogAttributes;
}

/**
* It prints a log item with level INFO.
*
Expand Down Expand Up @@ -417,11 +451,8 @@ class Logger extends Utility implements LoggerInterface {
context,
callback
) {
let initialPersistentAttributes = {};
if (options && options.clearState === true) {
initialPersistentAttributes = {
...loggerRef.getPersistentLogAttributes(),
};
loggerRef.clearState();
shdq marked this conversation as resolved.
Show resolved Hide resolved
}

Logger.injectLambdaContextBefore(loggerRef, event, context, options);
Expand All @@ -434,7 +465,7 @@ class Logger extends Utility implements LoggerInterface {
} finally {
Logger.injectLambdaContextAfterOrOnError(
loggerRef,
initialPersistentAttributes,
loggerRef.getPersistentLogAttributes(),
options
);
shdq marked this conversation as resolved.
Show resolved Hide resolved
}
Expand All @@ -446,11 +477,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);
shdq marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down Expand Up @@ -500,10 +532,11 @@ class Logger extends Utility implements LoggerInterface {
*/
public removeKeys(keys: string[]): void {
shdq marked this conversation as resolved.
Show resolved Hide resolved
this.removePersistentLogAttributes(keys);
this.removeTemporaryLogAttributes(keys);
}

/**
* It removes attributes based on provided keys to all log items generated by this Logger instance.
* It removes persistent attributes based on provided keys to all log items generated by this Logger instance.
*
* @param {string[]} keys
* @returns {void}
Expand All @@ -516,6 +549,20 @@ class Logger extends Utility implements LoggerInterface {
}
}

/**
* It removes temporary attributes based on provided keys to all log items generated by this Logger instance.
*
* @param {string[]} keys
* @returns {void}
*/
public removeTemporaryLogAttributes(keys: string[]): void {
shdq marked this conversation as resolved.
Show resolved Hide resolved
for (const key of keys) {
if (this.temporaryLogAttributes && key in this.temporaryLogAttributes) {
delete this.temporaryLogAttributes[key];
}
}
}

/**
* Set the log level for this Logger instance.
*
Expand All @@ -534,6 +581,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 +714,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 +1075,23 @@ class Logger extends Utility implements LoggerInterface {
serviceName,
sampleRateValue,
logFormatter,
persistentLogAttributes,
persistentKeys,
persistentLogAttributes, // deprecated in favor of persistentKeys
environment,
} = options;

if (persistentLogAttributes && persistentKeys) {
throw new Error(
shdq marked this conversation as resolved.
Show resolved Hide resolved
`Both persistentLogAttributes and persistentKeys options are provided. Use only persistentKeys as persistentLogAttributes is deprecated.`
);
}

// 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
13 changes: 4 additions & 9 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,10 +68,11 @@ const injectLambdaContext = (

const injectLambdaContextAfterOrOnError = async (): Promise<void> => {
if (isClearState) {
loggers.forEach((logger: Logger, index: number) => {
loggers.forEach((logger: Logger) => {
logger.clearState();
Logger.injectLambdaContextAfterOrOnError(
logger,
persistentAttributes[index],
logger.getPersistentLogAttributes(),
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
options
);
});
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