Skip to content

Commit a5615bb

Browse files
committed
doc: Custom function for unserializable values
1 parent 4090ea1 commit a5615bb

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

docs/core/logger.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,24 @@ If you prefer to log in a specific timezone, you can configure it by setting the
539539
--8<-- "examples/snippets/logger/customTimezoneOutput.json"
540540
```
541541

542+
### Custom function for unserializable values
543+
544+
By default, Logger uses `JSON.stringify()` to serialize log items. This means that `Map`, `Set` etc. will be serialized as `{}`, as detailed in the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description).
545+
546+
You can manage the serialization of these types by providing your own replacer function, which will be utilized during serialization.
547+
548+
=== "unserializableValues.ts"
549+
550+
```typescript hl_lines="4 7"
551+
--8<-- "examples/snippets/logger/unserializableValues.ts"
552+
```
553+
554+
=== "unserializableValues.json"
555+
556+
```json hl_lines="8"
557+
--8<-- "examples/snippets/logger/unserializableValues.json"
558+
```
559+
542560
### Using multiple Logger instances across your code
543561

544562
The `createChild` method allows you to create a child instance of the Logger, which inherits all of the attributes from its parent. You have the option to override any of the settings and attributes from the parent logger, including [its settings](#utility-settings), any [extra keys](#appending-additional-keys), and [the log formatter](#custom-log-formatter-bring-your-own-formatter).
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"level": "INFO",
3+
"message": "Serialize with custom serializer",
4+
"sampling_rate": 0,
5+
"service": "serverlessAirline",
6+
"timestamp": "2024-07-07T09:52:14.212Z",
7+
"xray_trace_id": "1-668a654d-396c646b760ee7d067f32f18",
8+
"serializedValue": [1, 2, 3]
9+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Logger } from '@aws-lambda-powertools/logger';
2+
import type { CustomReplacerFn } from '@aws-lambda-powertools/logger/types';
3+
4+
const jsonReplacerFn: CustomReplacerFn = (key: string, value: unknown) =>
5+
value instanceof Set ? [...value] : value;
6+
7+
const logger = new Logger({ serviceName: 'serverlessAirline', jsonReplacerFn });
8+
9+
export const handler = async (_event, _context): Promise<void> => {
10+
logger.info('Serialize with custom serializer', {
11+
serializedValue: new Set([1, 2, 3]),
12+
});
13+
};

0 commit comments

Comments
 (0)