-
Notifications
You must be signed in to change notification settings - Fork 1
/
json-format.js
86 lines (71 loc) · 2.07 KB
/
json-format.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
"use strict";
const { isoFormat } = require("./utils/strftime");
const stringify = require("./utils/safe-json-stringify");
const LEVELS = require("./levels");
const LEVELS_QUOTED = {};
Object.keys(LEVELS).forEach(function(level) {
LEVELS_QUOTED[level] = JSON.stringify(level);
});
const JSON_VERSION = "0";
const NAMES_QUOTTED_CACHE = {};
function jsonFormat(rec, __ser, opts) {
if (!(rec.logger in NAMES_QUOTTED_CACHE)) {
NAMES_QUOTTED_CACHE[rec.logger] = opts.stringify(rec.logger);
}
let msg =
"{" +
'"logger":' +
NAMES_QUOTTED_CACHE[rec.logger] +
',"level":' +
String(rec.level) +
',"levelname":' +
LEVELS_QUOTED[rec.levelname] +
',"message":' +
opts.stringify(rec.message) +
',"' +
opts.timestampKeyName +
'":' +
String(opts.stringify(__ser.timestamp(rec.timestamp))) +
',"v":' +
JSON_VERSION;
if (rec.err != null) {
msg +=
',"err":{"name":' +
opts.stringify(rec.err.name) +
',"message":' +
opts.stringify(rec.err.message) +
',"stack":' +
opts.stringify(rec.err.stack) +
"}";
}
if (rec.context != null) {
msg += ',"context":{';
const ctx = [];
for (const name in rec.context) {
const value = rec.context[name];
if (value === undefined) continue;
if (__ser.context != null && name in __ser.context) {
const res = __ser.context[name](value);
if (res === undefined) continue;
ctx.push(opts.stringify(name) + ":" + opts.stringify(res));
} else {
ctx.push(opts.stringify(name) + ":" + opts.stringify(value));
}
}
msg += ctx.join(",");
msg += "}";
}
msg += "}";
return msg;
}
module.exports = function createJsonFormat(serializers, opts) {
const o = opts || {};
o.stringify = o.stringify === "safe" ? stringify : JSON.stringify;
o.eol = o.eol == null ? "\n" : o.eol;
const s = serializers || {};
s.timestamp = s.timestamp || isoFormat;
o.timestampKeyName = o.timestampKeyName || "timestamp";
return function(record) {
return jsonFormat(record, s, o) + o.eol;
};
};