forked from pinojs/pino-pretty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
286 lines (238 loc) · 7.75 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
'use strict'
const chalk = require('chalk')
const dateformat = require('dateformat')
// remove jsonParser once Node 6 is not supported anymore
const jsonParser = require('fast-json-parse')
const jmespath = require('jmespath')
const CONSTANTS = require('./lib/constants')
const levels = {
default: 'USERLVL',
60: 'FATAL',
50: 'ERROR',
40: 'WARN ',
30: 'INFO ',
20: 'DEBUG',
10: 'TRACE'
}
const defaultOptions = {
colorize: chalk.supportsColor,
crlf: false,
errorLikeObjectKeys: ['err', 'error'],
errorProps: '',
levelFirst: false,
messageKey: CONSTANTS.MESSAGE_KEY,
translateTime: false,
useMetadata: false,
outputStream: process.stdout
}
function isObject (input) {
return Object.prototype.toString.apply(input) === '[object Object]'
}
function isPinoLog (log) {
return log && (log.hasOwnProperty('v') && log.v === 1)
}
function formatTime (epoch, translateTime) {
const instant = new Date(epoch)
if (translateTime === true) {
return dateformat(instant, 'UTC:' + CONSTANTS.DATE_FORMAT)
} else {
const upperFormat = translateTime.toUpperCase()
return (!upperFormat.startsWith('SYS:'))
? dateformat(instant, 'UTC:' + translateTime)
: (upperFormat === 'SYS:STANDARD')
? dateformat(instant, CONSTANTS.DATE_FORMAT)
: (upperFormat === 'SYS:COMPACT')
? dateformat(instant, CONSTANTS.DATE_FORMAT_COMPACT)
: dateformat(instant, translateTime.slice(4))
}
}
function nocolor (input) {
return input
}
module.exports = function prettyFactory (options) {
const opts = Object.assign({}, defaultOptions, options)
const EOL = opts.crlf ? '\r\n' : '\n'
const IDENT = ' '
const messageKey = opts.messageKey
const errorLikeObjectKeys = opts.errorLikeObjectKeys
const errorProps = opts.errorProps.split(',')
const color = {
default: nocolor,
60: nocolor,
50: nocolor,
40: nocolor,
30: nocolor,
20: nocolor,
10: nocolor,
message: nocolor,
channel: nocolor
}
if (opts.colorize) {
const ctx = new chalk.constructor({ enabled: true, level: 3 })
color.default = ctx.white
color[60] = ctx.magenta
color[50] = ctx.red
color[40] = ctx.yellow
color[30] = ctx.green
color[20] = ctx.blue
color[10] = ctx.grey
}
const search = opts.search
return pretty
function pretty (inputData) {
let log
if (!isObject(inputData)) {
const parsed = jsonParser(inputData)
log = parsed.value
if (parsed.err || !isPinoLog(log)) {
// pass through
return inputData + EOL
}
} else {
log = inputData
}
if (search && !jmespath.search(log, search)) {
return
}
const standardKeys = [
'channel',
'pid',
'hostname',
'name',
'level',
'time',
'v'
]
if (opts.translateTime) {
log.time = formatTime(log.time, opts.translateTime)
}
var line = log.time ? `[${log.time}]` : ''
line = opts.expandHighlight ? chalk.bgBlack(line) : chalk.grey(line)
const levelColor = levels.hasOwnProperty(log.level)
? color[log.level]
: color.default
let levelName = levels.hasOwnProperty(log.level)
? levels[log.level]
: levels.default
levelName = chalk.bgWhite.bold(` ${levelName} `)
if (!opts.expandHighlight) levelName = levelColor.inverse(levelName)
if (opts.levelFirst) {
line = `${levelName} ${line}`
} else {
// If the line is not empty (timestamps are enabled) output it
// with a space after it - otherwise output the empty string
const lineOrEmpty = line && line + ' '
line = `${lineOrEmpty}${levelName}`
}
if (opts.expandHighlight) line = levelColor.inverse(line)
if (!opts.compact && (log.name || log.pid || log.hostname)) {
line += ' ('
if (log.name) {
line += log.name
}
if (log.name && log.pid) {
line += '/' + log.pid
} else if (log.pid) {
line += log.pid
}
if (log.hostname) {
line += ' on ' + log.hostname
}
line += ')'
}
line += ' '
if (log.channel) {
line += chalk.bold(`${log.channel}: `)
}
if (log[messageKey] && typeof log[messageKey] === 'string') {
line += levelColor(log[messageKey])
}
line += EOL
if (log.type === 'Error' && log.stack) {
const stack = log.stack
line += IDENT + joinLinesWithIndentation(stack) + EOL
let propsForPrint
if (errorProps && errorProps.length > 0) {
// don't need print these props for 'Error' object
const excludedProps = standardKeys.concat([messageKey, 'type', 'stack'])
if (errorProps[0] === '*') {
// print all log props excluding 'excludedProps'
propsForPrint = Object.keys(log).filter((prop) => excludedProps.indexOf(prop) < 0)
} else {
// print props from 'errorProps' only
// but exclude 'excludedProps'
propsForPrint = errorProps.filter((prop) => excludedProps.indexOf(prop) < 0)
}
for (var i = 0; i < propsForPrint.length; i++) {
const key = propsForPrint[i]
if (!log.hasOwnProperty(key)) continue
if (log[key] instanceof Object) {
// call 'filterObjects' with 'excludeStandardKeys' = false
// because nested property might contain property from 'standardKeys'
line += IDENT + key + ': {' + EOL + filterObjects(log[key], '', errorLikeObjectKeys, false) + '}' + EOL
continue
}
line += IDENT + key + ': ' + log[key] + EOL
}
}
} else {
line += filterObjects(log, typeof log[messageKey] === 'string' ? messageKey : undefined, errorLikeObjectKeys)
}
if (opts.additionalLine) line += EOL;
return line
function joinLinesWithIndentation (value) {
const lines = value.split(/\r?\n/)
for (var i = 1; i < lines.length; i++) {
lines[i] = IDENT + lines[i]
}
return lines.join(EOL)
}
function filterObjects (value, messageKey, errorLikeObjectKeys, excludeStandardKeys) {
errorLikeObjectKeys = errorLikeObjectKeys || []
const keys = Object.keys(value)
const filteredKeys = []
if (messageKey) {
filteredKeys.push(messageKey)
}
if (excludeStandardKeys !== false) {
Array.prototype.push.apply(filteredKeys, standardKeys)
}
let result = ''
for (var i = 0; i < keys.length; i += 1) {
if (errorLikeObjectKeys.indexOf(keys[i]) !== -1 && value[keys[i]] !== undefined) {
const lines = JSON.stringify(value[keys[i]], null, 2)
if (lines === undefined) continue
const arrayOfLines = (
IDENT + keys[i] + ': ' +
joinLinesWithIndentation(lines) +
EOL
).split('\n')
for (var j = 0; j < arrayOfLines.length; j += 1) {
if (j !== 0) {
result += '\n'
}
const line = arrayOfLines[j]
if (/^\s*"stack"/.test(line)) {
const matches = /^(\s*"stack":)\s*(".*"),?$/.exec(line)
if (matches && matches.length === 3) {
const indentSize = /^\s*/.exec(line)[0].length + 4
const indentation = ' '.repeat(indentSize)
result += matches[1] + '\n' + indentation + JSON.parse(matches[2]).replace(/\n/g, '\n' + indentation)
}
} else {
result += line
}
}
} else if (filteredKeys.indexOf(keys[i]) < 0) {
if (value[keys[i]] !== undefined) {
const lines = JSON.stringify(value[keys[i]], null, 2)
if (lines !== undefined) {
result += IDENT + keys[i] + ': ' + joinLinesWithIndentation(lines) + EOL
}
}
}
}
return result
}
}
}