-
Notifications
You must be signed in to change notification settings - Fork 847
/
pino.js
482 lines (424 loc) · 11.8 KB
/
pino.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
'use strict'
var stringifySafe = require('fast-safe-stringify')
var format = require('quick-format-unescaped')
var EventEmitter = require('events').EventEmitter
var os = require('os')
var fs = require('fs')
var flatstr = require('flatstr')
var once = require('once')
var util = require('util')
var pid = process.pid
var hostname = os.hostname()
var baseLog = flatstr('{"pid":' + pid + ',"hostname":"' + hostname + '",')
var LOG_VERSION = 1
var defaultOptions = {
safe: true,
name: undefined,
serializers: {},
timestamp: true,
slowtime: false,
extreme: false,
level: 'info',
levelVal: undefined,
enabled: true
}
var levels = {
fatal: 60,
error: 50,
warn: 40,
info: 30,
debug: 20,
trace: 10
}
var nums = Object.keys(levels).reduce(function (o, k) {
o[levels[k]] = k
return o
}, {})
function defineLevelsProperty (onObject) {
Object.defineProperty(onObject, 'levels', {
value: {
values: copy({}, levels),
labels: copy({}, nums)
},
enumerable: true
})
Object.defineProperty(onObject.levels.values, 'silent', {value: 100})
Object.defineProperty(onObject.levels.labels, '100', {value: 'silent'})
}
// IIFE so the keys are cached at module load
var isStandardLevel = (function () {
var keys = Object.keys(levels)
return function (level) {
return keys.indexOf(level) > -1
}
}())
var isStandardLevelVal = (function () {
var keys = Object.keys(nums)
return function (val) {
return keys.indexOf(val + '') > -1
}
}())
// level string cache
var lscache = Object.keys(nums).reduce(function (o, k) {
o[k] = flatstr('"level":' + Number(k))
return o
}, {})
function streamIsBlockable (s) {
if (s.hasOwnProperty('_handle') && s._handle.hasOwnProperty('fd') && s._handle.fd) return true
if (s.hasOwnProperty('fd') && s.fd) return true
return false
}
function pino (opts, stream) {
var iopts = opts
var istream = stream
if (iopts && (iopts.writable || iopts._writableState)) {
istream = iopts
iopts = defaultOptions
}
istream = istream || process.stdout
iopts = Object.assign({}, defaultOptions, iopts)
// internal options
iopts.stringify = iopts.safe ? stringifySafe : JSON.stringify
iopts.formatOpts = {lowres: true}
iopts.end = ',"v":' + LOG_VERSION + '}\n'
iopts.cache = !iopts.extreme ? null : {
size: 4096,
buf: ''
}
iopts.chindings = ''
if (iopts.enabled === false) {
iopts.level = 'silent'
}
var logger = new Pino(iopts, istream)
if (iopts.cache) {
// setImmediate is causing a very weird crash:
// Assertion failed: (cb_v->IsFunction()), function MakeCallback...
// but setTimeout isn't *shrug*
setTimeout(function () {
if (!streamIsBlockable(istream)) {
logger.emit('error', new Error('stream must have a file descriptor in extreme mode'))
}
}, 100)
onExit(function (code, evt) {
var buf = iopts.cache.buf
if (buf) {
// We need to block the process exit long enough to flush the buffer
// to the destination stream. We do that by forcing a synchronous
// write directly to the stream's file descriptor.
var fd = (istream.fd) ? istream.fd : istream._handle.fd
fs.writeSync(fd, buf)
}
if (!process._events[evt] || process._events[evt].length < 2 || !process._events[evt].filter(function (f) {
return f + '' !== onExit.passCode + '' && f + '' !== onExit.insertCode + ''
}).length) {
process.exit(code)
} else {
return 'no exit'
}
})
}
return logger
}
defineLevelsProperty(pino)
function Pino (opts, stream) {
// We define the levels property at construction so that state does
// not get shared between instances.
defineLevelsProperty(this)
this.stream = stream
this.serializers = opts.serializers
this.stringify = opts.stringify
this.end = opts.end
this.name = opts.name
this.timestamp = opts.timestamp
this.slowtime = opts.slowtime
this.chindings = opts.chindings
this.cache = opts.cache
this.formatOpts = opts.formatOpts
if (opts.level && opts.levelVal) {
var levelIsStandard = isStandardLevel(opts.level)
var valIsStandard = isStandardLevelVal(opts.levelVal)
if (valIsStandard) throw new Error('level value is already used: ' + opts.levelVal)
if (levelIsStandard === false && valIsStandard === false) this.addLevel(opts.level, opts.levelVal)
}
this._setLevel(opts.level)
this._baseLog = flatstr(baseLog +
(this.name === undefined ? '' : '"name":' + this.stringify(this.name) + ','))
if (opts.timestamp === false) {
this.time = getNoTime
} else if (opts.slowtime) {
this.time = getSlowTime
} else {
this.time = getTime
}
}
Pino.prototype = new EventEmitter()
Pino.prototype.fatal = genLog(levels.fatal)
Pino.prototype.error = genLog(levels.error)
Pino.prototype.warn = genLog(levels.warn)
Pino.prototype.info = genLog(levels.info)
Pino.prototype.debug = genLog(levels.debug)
Pino.prototype.trace = genLog(levels.trace)
Object.defineProperty(Pino.prototype, 'levelVal', {
get: function getLevelVal () {
return this._levelVal
},
set: function setLevelVal (num) {
if (typeof num === 'string') { return this._setLevel(num) }
if (this.emit) {
this.emit('level-change', this.levels.labels[num], num, this.levels.labels[this._levelVal], this._levelVal)
}
this._levelVal = num
for (var key in this.levels.values) {
if (num > this.levels.values[key]) {
this[key] = noop
continue
}
this[key] = isStandardLevel(key) ? Pino.prototype[key] : genLog(num)
}
}
})
Pino.prototype._setLevel = function _setLevel (level) {
if (typeof level === 'number') { level = this.levels.labels[level] }
if (!this.levels.values[level]) {
throw new Error('unknown level ' + level)
}
this.levelVal = this.levels.values[level]
}
Pino.prototype._getLevel = function _getLevel (level) {
return this.levels.labels[this.levelVal]
}
Object.defineProperty(Pino.prototype, 'level', {
get: Pino.prototype._getLevel,
set: Pino.prototype._setLevel
})
Object.defineProperty(Pino.prototype, '_lscache', {
value: copy({}, lscache)
})
Object.defineProperty(
Pino.prototype,
'LOG_VERSION',
{value: LOG_VERSION}
)
Pino.prototype.asJson = function asJson (obj, msg, num) {
if (!msg && obj instanceof Error) {
msg = obj.message
}
var data = this._baseLog + this._lscache[num] + this.time()
// to catch both null and undefined
/* eslint-disable eqeqeq */
if (msg != undefined) {
data += ',"msg":' + JSON.stringify('' + msg)
}
var value
if (obj) {
if (obj.stack) {
data += ',"type":"Error","stack":' + this.stringify(obj.stack)
}
for (var key in obj) {
value = obj[key]
if (obj.hasOwnProperty(key) && value !== undefined) {
value = this.stringify(this.serializers[key] ? this.serializers[key](value) : value)
if (value !== undefined) {
data += ',"' + key + '":' + value
}
}
}
}
return data + this.chindings + this.end
}
function getNoTime () {
return ''
}
function getTime () {
return ',"time":' + Date.now()
}
function getSlowTime () {
return ',"time":"' + (new Date()).toISOString() + '"'
}
Pino.prototype.child = function child (bindings) {
if (!bindings) {
throw new Error('missing bindings for child Pino')
}
var data = ','
var value
var key
for (key in bindings) {
value = bindings[key]
if (key !== 'level' && key !== 'serializers' && bindings.hasOwnProperty(key) && value !== undefined) {
value = this.serializers[key] ? this.serializers[key](value) : value
data += '"' + key + '":' + this.stringify(value) + ','
}
}
data = this.chindings + data.substr(0, data.length - 1)
var opts = {
level: bindings.level || this.level,
levelVal: isStandardLevelVal(this.levelVal) ? undefined : this.levelVal,
serializers: bindings.hasOwnProperty('serializers') ? Object.assign(this.serializers, bindings.serializers) : this.serializers,
stringify: this.stringify,
end: this.end,
name: this.name,
timestamp: this.timestamp,
slowtime: this.slowtime,
chindings: data,
cache: this.cache,
formatOpts: this.formatOpts
}
return new Pino(opts, this.stream)
}
Pino.prototype.write = function (obj, msg, num) {
var s = this.asJson(obj, msg, num)
if (!this.cache) {
this.stream.write(flatstr(s))
return
}
this.cache.buf += s
if (this.cache.buf.length > this.cache.size) {
this.stream.write(flatstr(this.cache.buf))
this.cache.buf = ''
}
}
Pino.prototype.flush = function () {
if (!this.cache) {
return
}
this.stream.write(flatstr(this.cache.buf))
this.cache.buf = ''
}
Pino.prototype.addLevel = function addLevel (name, lvl) {
if (this.levels.values.hasOwnProperty(name)) return false
if (this.levels.labels.hasOwnProperty(lvl)) return false
this.levels.values[name] = lvl
this.levels.labels[lvl] = name
this._lscache[lvl] = flatstr('"level":' + Number(lvl))
this[name] = genLog(lvl)
return true
}
function mapHttpRequest (req) {
return {
req: asReqValue(req)
}
}
function mapHttpResponse (res) {
return {
res: asResValue(res)
}
}
function asReqValue (req) {
return {
method: req.method,
url: req.url,
headers: req.headers,
remoteAddress: req.connection.remoteAddress,
remotePort: req.connection.remotePort
}
}
function asResValue (res) {
return {
statusCode: res.statusCode,
header: res._header
}
}
function asErrValue (err) {
var obj = {
type: err.constructor.name,
message: err.message,
stack: err.stack
}
for (var key in err) {
if (obj[key] === undefined) {
obj[key] = err[key]
}
}
return obj
}
function countInterp (s, i) {
var n = 0
var pos = 0
while (true) {
pos = s.indexOf(i, pos)
if (pos >= 0) {
++n
pos += 2
} else break
}
return n
}
function genLog (z) {
return function LOG (a, b, c, d, e, f, g, h, i, j, k) {
var l = 0
var m = null
var n = null
var o
var p
if (typeof a === 'object' && a !== null) {
m = a
n = [b, c, d, e, f, g, h, i, j, k]
l = 1
if (m.method && m.headers && m.socket) {
m = mapHttpRequest(m)
} else if (m.statusCode) {
m = mapHttpResponse(m)
}
} else {
n = [a, b, c, d, e, f, g, h, i, j, k]
}
p = n.length = arguments.length - l
if (p > 1) {
l = typeof a === 'string' ? countInterp(a, '%j') : 0
if (l) {
n.length = l + countInterp(a, '%d') + countInterp(a, '%s') + 1
o = `${util.format.apply(null, n)}`
} else {
o = format(n, this.formatOpts)
}
} else if (p) {
o = n[0]
}
this.write(m, o, z)
}
}
function copy (a, b) {
for (var k in b) { a[k] = b[k] }
return a
}
function onExit (fn) {
var oneFn = once(fn)
process.on('beforeExit', handle('beforeExit'))
process.on('exit', handle('exit'))
process.on('uncaughtException', handle('uncaughtException', 1))
process.on('SIGHUP', handle('SIGHUP', 129))
process.on('SIGINT', handle('SIGINT', 130))
process.on('SIGQUIT', handle('SIGQUIT', 131))
process.on('SIGTERM', handle('SIGTERM', 143))
function handle (evt, code) {
onExit.passCode = function (code) {
if (oneFn.value) { oneFn = once(fn) }
oneFn(code, evt)
}
onExit.insertCode = function () {
if (oneFn.value) { oneFn = once(fn) }
oneFn(code, evt)
}
return (code === undefined) ? onExit.passCode : onExit.insertCode
}
}
function noop () {}
module.exports = pino
module.exports.stdSerializers = {
req: asReqValue,
res: asResValue,
err: asErrValue
}
module.exports.pretty = require('./pretty')
Object.defineProperty(
module.exports,
'LOG_VERSION',
{value: LOG_VERSION, enumerable: true}
)
// This is an internal API. It can change at any time, including semver-minor.
// Use it at your own risk.
Object.defineProperty(
module.exports,
'_Pino',
{value: Pino}
)