Skip to content

Commit 2f66bba

Browse files
committed
chore: address PR review
1 parent 96bd30d commit 2f66bba

File tree

6 files changed

+90
-196
lines changed

6 files changed

+90
-196
lines changed

docs/core/logger.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -547,7 +547,7 @@ You can manage the serialization of these types by providing your own replacer f
547547

548548
=== "unserializableValues.ts"
549549

550-
```typescript hl_lines="4 7"
550+
```typescript hl_lines="4-5 7"
551551
--8<-- "examples/snippets/logger/unserializableValues.ts"
552552
```
553553

examples/snippets/logger/unserializableValues.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import { Logger } from '@aws-lambda-powertools/logger';
22
import type { CustomReplacerFn } from '@aws-lambda-powertools/logger/types';
33

4-
const jsonReplacerFn: CustomReplacerFn = (key: string, value: unknown) =>
4+
const jsonReplacerFn: CustomReplacerFn = (_: string, value: unknown) =>
55
value instanceof Set ? [...value] : value;
66

77
const logger = new Logger({ serviceName: 'serverlessAirline', jsonReplacerFn });
88

9-
export const handler = async (_event, _context): Promise<void> => {
9+
export const handler = async (): Promise<void> => {
1010
logger.info('Serialize with custom serializer', {
1111
serializedValue: new Set([1, 2, 3]),
1212
});

packages/logger/src/Logger.ts

Lines changed: 40 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import type {
2424
LogItemMessage,
2525
LoggerInterface,
2626
PowertoolsLogData,
27-
CustomReplacerFn,
27+
CustomJsonReplacerFn,
2828
} from './types/Logger.js';
2929

3030
/**
@@ -115,10 +115,6 @@ import type {
115115
* @see https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/
116116
*/
117117
class Logger extends Utility implements LoggerInterface {
118-
/**
119-
* Replacer function used to serialize the log items.
120-
*/
121-
protected jsonReplacerFn?: CustomReplacerFn;
122118
/**
123119
* Console instance used to print logs.
124120
*
@@ -205,6 +201,10 @@ class Logger extends Utility implements LoggerInterface {
205201
* We keep this value to be able to reset the log level to the initial value when the sample rate is refreshed.
206202
*/
207203
#initialLogLevel = 12;
204+
/**
205+
* Replacer function used to serialize the log items.
206+
*/
207+
#jsonReplacerFn?: CustomJsonReplacerFn;
208208

209209
/**
210210
* Log level used by the current instance of Logger.
@@ -314,7 +314,7 @@ class Logger extends Utility implements LoggerInterface {
314314
environment: this.powertoolsLogData.environment,
315315
persistentLogAttributes: this.persistentLogAttributes,
316316
temporaryLogAttributes: this.temporaryLogAttributes,
317-
jsonReplacerFn: this.jsonReplacerFn,
317+
jsonReplacerFn: this.#jsonReplacerFn,
318318
},
319319
options
320320
)
@@ -680,6 +680,38 @@ class Logger extends Utility implements LoggerInterface {
680680
return new Logger(options);
681681
}
682682

683+
/**
684+
* When the data added in the log item contains object references or BigInt values,
685+
* `JSON.stringify()` can't handle them and instead throws errors:
686+
* `TypeError: cyclic object value` or `TypeError: Do not know how to serialize a BigInt`.
687+
* To mitigate these issues, this method will find and remove all cyclic references and convert BigInt values to strings.
688+
*
689+
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#exceptions
690+
* @private
691+
*/
692+
protected getJsonReplacer(): (key: string, value: unknown) => void {
693+
const references = new WeakSet();
694+
695+
return (key, value) => {
696+
if (this.#jsonReplacerFn) value = this.#jsonReplacerFn?.(key, value);
697+
698+
if (value instanceof Error) {
699+
value = this.getLogFormatter().formatError(value);
700+
}
701+
if (typeof value === 'bigint') {
702+
return value.toString();
703+
}
704+
if (typeof value === 'object' && value !== null) {
705+
if (references.has(value)) {
706+
return;
707+
}
708+
references.add(value);
709+
}
710+
711+
return value;
712+
};
713+
}
714+
683715
/**
684716
* It stores information that is printed in all log items.
685717
*
@@ -789,40 +821,6 @@ class Logger extends Utility implements LoggerInterface {
789821
return this.customConfigService;
790822
}
791823

792-
/**
793-
* When the data added in the log item contains object references or BigInt values,
794-
* `JSON.stringify()` can't handle them and instead throws errors:
795-
* `TypeError: cyclic object value` or `TypeError: Do not know how to serialize a BigInt`.
796-
* To mitigate these issues, this method will find and remove all cyclic references and convert BigInt values to strings.
797-
*
798-
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#exceptions
799-
* @private
800-
*/
801-
private getDefaultReplacer(): (
802-
key: string,
803-
value: LogAttributes | Error | bigint
804-
) => void {
805-
const references = new WeakSet();
806-
807-
return (key, value) => {
808-
let item = value;
809-
if (item instanceof Error) {
810-
item = this.getLogFormatter().formatError(item);
811-
}
812-
if (typeof item === 'bigint') {
813-
return item.toString();
814-
}
815-
if (typeof item === 'object' && value !== null) {
816-
if (references.has(item)) {
817-
return;
818-
}
819-
references.add(item);
820-
}
821-
822-
return item;
823-
};
824-
}
825-
826824
/**
827825
* It returns the instance of a service that fetches environment variables.
828826
*
@@ -926,7 +924,7 @@ class Logger extends Utility implements LoggerInterface {
926924
this.console[consoleMethod](
927925
JSON.stringify(
928926
log.getAttributes(),
929-
this.jsonReplacerFn,
927+
this.getJsonReplacer(),
930928
this.logIndentation
931929
)
932930
);
@@ -1150,7 +1148,7 @@ class Logger extends Utility implements LoggerInterface {
11501148
this.setLogFormatter(logFormatter);
11511149
this.setConsole();
11521150
this.setLogIndentation();
1153-
this.#setJsonReplacerFn(jsonReplacerFn);
1151+
this.#jsonReplacerFn = jsonReplacerFn;
11541152

11551153
return this;
11561154
}
@@ -1183,16 +1181,6 @@ class Logger extends Utility implements LoggerInterface {
11831181
});
11841182
this.appendPersistentKeys(persistentLogAttributes);
11851183
}
1186-
1187-
/**
1188-
* It sets the JSON replacer function which is used to serialize the log items.
1189-
* @private
1190-
* @param customerReplacerFn
1191-
*/
1192-
#setJsonReplacerFn(customerReplacerFn?: CustomReplacerFn): void {
1193-
this.jsonReplacerFn =
1194-
customerReplacerFn ?? (this.getDefaultReplacer() as CustomReplacerFn);
1195-
}
11961184
}
11971185

11981186
export { Logger };

packages/logger/src/types/Logger.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,13 @@ type InjectLambdaContextOptions = {
2828
resetKeys?: boolean;
2929
};
3030

31-
type CustomReplacerFn = (key: string, value: unknown) => void;
31+
/**
32+
* A custom JSON replacer function that can be passed to the Logger constructor.
33+
*
34+
* @param key - The key of the value being stringified.
35+
* @param value - The value being stringified.
36+
*/
37+
type CustomJsonReplacerFn = (key: string, value: unknown) => unknown;
3238

3339
type BaseConstructorOptions = {
3440
logLevel?: LogLevel;
@@ -37,7 +43,10 @@ type BaseConstructorOptions = {
3743
logFormatter?: LogFormatterInterface;
3844
customConfigService?: ConfigServiceInterface;
3945
environment?: Environment;
40-
jsonReplacerFn?: CustomReplacerFn;
46+
/**
47+
* A custom JSON replacer function that can be passed to the Logger constructor.
48+
*/
49+
jsonReplacerFn?: CustomJsonReplacerFn;
4150
};
4251

4352
type PersistentKeysOption = {
@@ -142,5 +151,5 @@ export type {
142151
PowertoolsLogData,
143152
ConstructorOptions,
144153
InjectLambdaContextOptions,
145-
CustomReplacerFn,
154+
CustomJsonReplacerFn,
146155
};

packages/logger/src/types/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,5 @@ export type {
1414
PowertoolsLogData,
1515
ConstructorOptions,
1616
InjectLambdaContextOptions,
17-
CustomReplacerFn,
17+
CustomJsonReplacerFn,
1818
} from './Logger.js';

0 commit comments

Comments
 (0)