-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (83 loc) · 2.02 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const pino = require('pino');
const merge = require('merge');
const parsetrace = require('parsetrace');
function getStack(err) {
if (!err.stack) return;
try {
const frames = parsetrace(err).object().frames;
return frames.map(f => `${f.function} :: ${f.file}:${f.line}`);
} catch (error) {
return err.stack.split('\n');
}
}
function errorWithStackSerializer(err) {
return {
type: err.type,
status: err.status,
message: err.message,
stack: getStack(err),
previous: err.previous ? errorWithStackSerializer(err.previous) : undefined,
reference: err.reference,
upstream: err.upstream,
};
}
function errSerializer(err) {
return {
type: err.type,
status: err.status,
message: err.message,
previous: err.previous ? errSerializer(err.previous) : undefined,
reference: err.reference,
upstream: err.upstream,
};
}
function reqSerializer(req) {
if (!req || !req.connection) {
return req;
}
return {
method: req.method,
url: req.url,
remoteAddress: req.connection.remoteAddress,
};
}
module.exports = function (config = {}) {
if (config.level) {
config.level = config.level.toLowerCase();
}
const { stack } = config;
const serializerForErrors = stack === false ? errSerializer : errorWithStackSerializer;
const logger = pino(merge.recursive({
timestamp: pino.stdTimeFunctions.isoTime,
mixin (mergeObject, level) {
return { severity: pino.levels.labels[level] }
},
formatters: {
log: (record) => {
record.err = record.err ? serializerForErrors(record.err) : undefined
record.req = record.req ? reqSerializer(record.req) : undefined
record.error = record.error ? serializerForErrors(record.error) : undefined
return record;
},
},
transport: {
targets: [
{
level: 'error',
target: 'pino/file',
options: { destination: 2 } // stderr
},
{
level: 'debug',
target: 'pino/file',
options: { destination: 1 } // stdout
},
],
dedupe: true,
},
}, config));
if (config.level) {
logger.level = config.level;
}
return logger;
}