Skip to content

Commit fabbcb5

Browse files
authored
feat: allow custom request data (#14)
- allow custom request data to be tracked on log entries - allow removing the default tracked data if needed
1 parent eff28ef commit fabbcb5

File tree

4 files changed

+95
-4
lines changed

4 files changed

+95
-4
lines changed

README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,48 @@ across the entire platform.
114114

115115
Amazon XRAY also has a unique tracing ID that is propagated across the requests and can be tracked as well.
116116

117+
## Customize request tracing
118+
119+
You can customize the data that is tracked for each request by adding a per-request mixin.
120+
The request mixin takes the Lambda `event` and `context` and returns an object.
121+
122+
This differs from the built in [pino mixin](https://github.com/pinojs/pino/blob/master/docs/api.md#mixin-function) as it only executes
123+
once per request where the built in pino mixin runs once per log entry.
124+
125+
```ts
126+
import pino from 'pino-lambda';
127+
const logger = pino({
128+
requestMixin: (event, context) => {
129+
return {
130+
// add request header host name
131+
host: event.headers?.host,
132+
133+
// you can also set any request property to undefined
134+
// which will remove it from the output
135+
'x-correlation-id': undefined,
136+
137+
// add any type of static data
138+
brand: 'famicom'
139+
};
140+
}
141+
});
142+
```
143+
144+
Output
145+
146+
```
147+
2018-12-20T17:05:25.330Z 6fccb00e-0479-11e9-af91-d7ab5c8fe19e INFO A log message
148+
{
149+
"awsRequestId": "6fccb00e-0479-11e9-af91-d7ab5c8fe19e",
150+
"x-correlation-trace-id": "Root=1-5c1bcbd2-9cce3b07143efd5bea1224f2;Parent=07adc05e4e92bf13;Sampled=1",
151+
"level": 30,
152+
"host": "www.host.com",
153+
"brand": "famicom",
154+
"message": "Some A log message",
155+
"data": "Some data"
156+
}
157+
```
158+
117159
## Downstream Request Debugging
118160

119161
When upstream services invoke a Lambda using `pino-lambda` they can send the `x-correlation-debug` header with a value of `true`. This will enable `debug` logging for that specific request. This is useful for tracing issues across the platform.

src/index.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import pino, { DestinationStream, LevelMapping, LoggerOptions, Logger } from 'pi
22
import { GlobalContextStorageProvider, ContextStorageProvider, ContextMap } from './context';
33

44
export interface ExtendedPinoOptions extends LoggerOptions {
5+
requestMixin?: (
6+
event: LamdbaEvent,
7+
context: LambdaContext,
8+
) => { [key: string]: string | undefined };
59
storageProvider?: ContextStorageProvider;
610
streamWriter?: (str: string | Uint8Array) => boolean;
711
}
@@ -148,6 +152,16 @@ export default (extendedPinoOptions?: ExtendedPinoOptions): PinoLambdaLogger =>
148152
logger.level = configuredLevel;
149153
}
150154

155+
// handle custom request level mixins
156+
if (pinoOptions.requestMixin) {
157+
const result = pinoOptions.requestMixin(event, context);
158+
for (const key in result) {
159+
// Cast this to string for typescript
160+
// when the JSON serializer runs, by default it omits undefined properties
161+
ctx[key] = result[key] as string;
162+
}
163+
}
164+
151165
storageProvider.setContext(ctx);
152166
};
153167
return logger;

src/tests/index.spec.ts

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ tap.test('should add tags with a child logger', (t) => {
7272
tap.test('should preserve mixins', (t) => {
7373
let n = 0;
7474
const [log, output] = createLogger({
75-
mixin () {
76-
return { line: ++n }
77-
}
75+
mixin() {
76+
return { line: ++n };
77+
},
7878
});
7979

8080
log.withRequest({}, { awsRequestId: '431234' });
@@ -86,7 +86,7 @@ tap.test('should preserve mixins', (t) => {
8686

8787
tap.test('should capture xray trace IDs', (t) => {
8888
process.env._X_AMZN_TRACE_ID = 'x-1-2e2323r1234r4';
89-
89+
9090
const [log, output] = createLogger();
9191

9292
log.withRequest({}, { awsRequestId: '431234' });
@@ -97,6 +97,33 @@ tap.test('should capture xray trace IDs', (t) => {
9797
t.end();
9898
});
9999

100+
tap.test('should capture custom request data', (t) => {
101+
const [log, output] = createLogger({
102+
requestMixin: (event, context) => ({
103+
host: event.headers?.host,
104+
functionName: context.functionName,
105+
}),
106+
});
107+
108+
log.withRequest({ headers: { host: 'www.host.com' } }, { awsRequestId: '431234' });
109+
log.info('Message with trace ID');
110+
t.matchSnapshot(output.buffer);
111+
t.end();
112+
});
113+
114+
tap.test('should allow removing default request data', (t) => {
115+
const [log, output] = createLogger({
116+
requestMixin: () => ({
117+
'x-correlation-id': undefined,
118+
}),
119+
});
120+
121+
log.withRequest({}, { awsRequestId: '431234' });
122+
log.info('Message with trace ID');
123+
t.matchSnapshot(output.buffer);
124+
t.end();
125+
});
126+
100127
/**
101128
* Creates a test logger and output buffer for assertions
102129
* Returns the logger and the buffer

tap-snapshots/src-tests-index.spec.ts-TAP.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ exports[`src/tests/index.spec.ts TAP should add tags with a child logger > must
99
2016-12-01T06:00:00.000Z 9048989 INFO Message with userId {"level":30,"time":1480572000000,"userId":12,"awsRequestId":"9048989","x-correlation-id":"9048989","msg":"Message with userId"}
1010
`
1111

12+
exports[`src/tests/index.spec.ts TAP should allow removing default request data > must match snapshot 1`] = `
13+
2016-12-01T06:00:00.000Z 431234 INFO Message with trace ID {"level":30,"time":1480572000000,"awsRequestId":"431234","x-correlation-trace-id":"undefined","msg":"Message with trace ID"}
14+
`
15+
16+
exports[`src/tests/index.spec.ts TAP should capture custom request data > must match snapshot 1`] = `
17+
2016-12-01T06:00:00.000Z 431234 INFO Message with trace ID {"level":30,"time":1480572000000,"awsRequestId":"431234","x-correlation-trace-id":"undefined","x-correlation-id":"431234","host":"www.host.com","msg":"Message with trace ID"}
18+
`
19+
1220
exports[`src/tests/index.spec.ts TAP should capture xray trace IDs > must match snapshot 1`] = `
1321
2016-12-01T06:00:00.000Z 431234 INFO Message with trace ID {"level":30,"time":1480572000000,"awsRequestId":"431234","x-correlation-trace-id":"x-1-2e2323r1234r4","x-correlation-id":"431234","msg":"Message with trace ID"}
1422
`

0 commit comments

Comments
 (0)