-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlog.js
50 lines (42 loc) · 1.22 KB
/
log.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const { createLogger, stdSerializers } = require('bunyan');
const { createNamespace, getNamespace } = require('cls-hooked');
const namespaceName = process.env.service__namespace || 'default-ns';
const ns = getNamespace(namespaceName) || createNamespace(namespaceName);
const log = createLogger({
name: process.env.logger__name || 'defaultLogger',
src: process.env.NODE_ENV !== 'production',
serializers: { err: stdSerializers.err },
streams: [
{
level: process.env.logger__level || 'info',
stream: process.stdout
}
]
});
const wrapIfError = obj =>
obj instanceof Error
? {
err: obj
}
: obj;
const decorator = fn => (first, ...rest) => {
const context = {
requestId: ns.get('requestId')
};
const args = [
...(typeof first === 'object'
? [
{
...wrapIfError(first),
context
}
]
: [{ context }, first]),
...rest
];
return fn.apply(log, args);
};
['trace', 'debug', 'info', 'warn', 'error', 'fatal'].forEach(name => {
log[name] = decorator(log[name]);
});
module.exports = log;