Skip to content

Commit c008055

Browse files
committed
Support field customization
Support customization of fields on a per-request basis
1 parent abf8e98 commit c008055

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

packages/ecs-morgan-format/index.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { IncomingMessage, ServerResponse } from 'http';
12
import type { FormatFn } from "morgan";
23

34
interface Config {
@@ -42,6 +43,8 @@ interface Config {
4243
/** Specify "event.dataset" field. Defaults `${serviceName}`. */
4344
eventDataset?: string;
4445

46+
/** Callback for custom modification of the fields */
47+
logHook: (event: { record: any, req: IncomingMessage, res: ServerResponse }) => void;
4548
}
4649

4750
declare function ecsFormat(config?: Config): FormatFn;

packages/ecs-morgan-format/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,8 @@ function ecsFormat (opts) {
175175
formatHttpRequest(ecsFields, req)
176176
formatHttpResponse(ecsFields, res)
177177

178+
opts.logHook && opts.logHook({ record: ecsFields, req, res })
179+
178180
return stringify(ecsFields)
179181
}
180182
}

packages/ecs-morgan-format/test/basic.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,3 +235,26 @@ test('can configure correlation fields', t => {
235235
t.end()
236236
})
237237
})
238+
239+
test('can provide custom fields', t => {
240+
t.plan(2)
241+
242+
const stream = split().on('data', line => {
243+
const rec = JSON.parse(line)
244+
t.equal(rec.labels.custom, 'customValue')
245+
})
246+
const logger = morgan(
247+
ecsFormat({
248+
logHook ({ record, req, res }) {
249+
record.labels = record.labels || {}
250+
record.labels.custom = 'customValue'
251+
}
252+
}),
253+
{ stream }
254+
)
255+
256+
makeExpressServerAndRequest(logger, '/', {}, null, function (err) {
257+
t.error(err)
258+
t.end()
259+
})
260+
})

0 commit comments

Comments
 (0)