react-hook-eslint 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/api.md ADDED
@@ -0,0 +1,1487 @@
1
+ # API
2
+
3
+ * [pino() => logger](#export)
4
+ * [options](#options)
5
+ * [destination](#destination)
6
+ * [destination\[Symbol.for('pino.metadata')\]](#metadata)
7
+ * [Logger Instance](#logger)
8
+ * [logger.trace()](#trace)
9
+ * [logger.debug()](#debug)
10
+ * [logger.info()](#info)
11
+ * [logger.warn()](#warn)
12
+ * [logger.error()](#error)
13
+ * [logger.fatal()](#fatal)
14
+ * [logger.silent()](#silent)
15
+ * [logger.child()](#child)
16
+ * [logger.bindings()](#logger-bindings)
17
+ * [logger.setBindings()](#logger-set-bindings)
18
+ * [logger.flush()](#flush)
19
+ * [logger.level](#logger-level)
20
+ * [logger.isLevelEnabled()](#islevelenabled)
21
+ * [logger.levels](#levels)
22
+ * [logger\[Symbol.for('pino.serializers')\]](#serializers)
23
+ * [Event: 'level-change'](#level-change)
24
+ * [logger.version](#version)
25
+ * [Statics](#statics)
26
+ * [pino.destination()](#pino-destination)
27
+ * [pino.transport()](#pino-transport)
28
+ * [pino.multistream()](#pino-multistream)
29
+ * [pino.stdSerializers](#pino-stdserializers)
30
+ * [pino.stdTimeFunctions](#pino-stdtimefunctions)
31
+ * [pino.symbols](#pino-symbols)
32
+ * [pino.version](#pino-version)
33
+ * [Interfaces](#interfaces)
34
+ * [MultiStreamRes](#multistreamres)
35
+ * [StreamEntry](#streamentry)
36
+ * [DestinationStream](#destinationstream)
37
+ * [Types](#types)
38
+ * [Level](#level-1)
39
+
40
+ <a id="export"></a>
41
+ ## `pino([options], [destination]) => logger`
42
+
43
+ The exported `pino` function takes two optional arguments,
44
+ [`options`](#options) and [`destination`](#destination), and
45
+ returns a [logger instance](#logger).
46
+
47
+ <a id=options></a>
48
+ ### `options` (Object)
49
+
50
+ #### `name` (String)
51
+
52
+ Default: `undefined`
53
+
54
+ The name of the logger. When set adds a `name` field to every JSON line logged.
55
+
56
+ #### `level` (String)
57
+
58
+ Default: `'info'`
59
+
60
+ The minimum level to log: Pino will not log messages with a lower level. Setting this option reduces the load, as typically, debug and trace logs are only valid for development, and not needed in production.
61
+
62
+ One of `'fatal'`, `'error'`, `'warn'`, `'info'`, `'debug'`, `'trace'` or `'silent'`.
63
+
64
+ Additional levels can be added to the instance via the `customLevels` option.
65
+
66
+ * See [`customLevels` option](#opt-customlevels)
67
+
68
+ <a id=opt-customlevels></a>
69
+
70
+ #### `levelComparison` ("ASC", "DESC", Function)
71
+
72
+ Default: `ASC`
73
+
74
+ Use this option to customize levels order.
75
+ In order to be able to define custom levels ordering pass a function which will accept `current` and `expected` values and return `boolean` which shows should `current` level to be shown or not.
76
+
77
+ ```js
78
+ const logger = pino({
79
+ levelComparison: 'DESC',
80
+ customLevels: {
81
+ foo: 20, // `foo` is more valuable than `bar`
82
+ bar: 10
83
+ },
84
+ })
85
+
86
+ // OR
87
+
88
+ const logger = pino({
89
+ levelComparison: function(current, expected) {
90
+ return current >= expected;
91
+ }
92
+ })
93
+ ```
94
+
95
+ #### `customLevels` (Object)
96
+
97
+ Default: `undefined`
98
+
99
+ Use this option to define additional logging levels.
100
+ The keys of the object correspond to the namespace of the log level,
101
+ and the values should be the numerical value of the level.
102
+
103
+ ```js
104
+ const logger = pino({
105
+ customLevels: {
106
+ foo: 35
107
+ }
108
+ })
109
+ logger.foo('hi')
110
+ ```
111
+
112
+ <a id=opt-useOnlyCustomLevels></a>
113
+ #### `useOnlyCustomLevels` (Boolean)
114
+
115
+ Default: `false`
116
+
117
+ Use this option to only use defined `customLevels` and omit Pino's levels.
118
+ Logger's default `level` must be changed to a value in `customLevels` to use `useOnlyCustomLevels`
119
+ Warning: this option may not be supported by downstream transports.
120
+
121
+ ```js
122
+ const logger = pino({
123
+ customLevels: {
124
+ foo: 35
125
+ },
126
+ useOnlyCustomLevels: true,
127
+ level: 'foo'
128
+ })
129
+ logger.foo('hi')
130
+ logger.info('hello') // Will throw an error saying info is not found in logger object
131
+ ```
132
+ #### `depthLimit` (Number)
133
+
134
+ Default: `5`
135
+
136
+ Option to limit stringification at a specific nesting depth when logging circular objects.
137
+
138
+ #### `edgeLimit` (Number)
139
+
140
+ Default: `100`
141
+
142
+ Option to limit stringification of properties/elements when logging a specific object/array with circular references.
143
+
144
+ <a id="opt-mixin"></a>
145
+ #### `mixin` (Function):
146
+
147
+ Default: `undefined`
148
+
149
+ If provided, the `mixin` function is called each time one of the active
150
+ logging methods is called. The first parameter is the value `mergeObject` or an empty object. The second parameter is the log level number.
151
+ The third parameter is the logger or child logger itself, which can be used to
152
+ retrieve logger-specific context from within the `mixin` function.
153
+ The function must synchronously return an object. The properties of the returned object will be added to the
154
+ logged JSON.
155
+
156
+ ```js
157
+ let n = 0
158
+ const logger = pino({
159
+ mixin () {
160
+ return { line: ++n }
161
+ }
162
+ })
163
+ logger.info('hello')
164
+ // {"level":30,"time":1573664685466,"pid":78742,"hostname":"x","line":1,"msg":"hello"}
165
+ logger.info('world')
166
+ // {"level":30,"time":1573664685469,"pid":78742,"hostname":"x","line":2,"msg":"world"}
167
+ ```
168
+
169
+ The result of `mixin()` is supposed to be a _new_ object. For performance reason, the object returned by `mixin()` will be mutated by pino.
170
+ In the following example, passing `mergingObject` argument to the first `info` call will mutate the global `mixin` object by default:
171
+ (* See [`mixinMergeStrategy` option](#opt-mixin-merge-strategy)):
172
+ ```js
173
+ const mixin = {
174
+ appName: 'My app'
175
+ }
176
+
177
+ const logger = pino({
178
+ mixin() {
179
+ return mixin;
180
+ }
181
+ })
182
+
183
+ logger.info({
184
+ description: 'Ok'
185
+ }, 'Message 1')
186
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","appName":"My app","description":"Ok","msg":"Message 1"}
187
+ logger.info('Message 2')
188
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","appName":"My app","description":"Ok","msg":"Message 2"}
189
+ // Note: the second log contains "description":"Ok" text, even if it was not provided.
190
+ ```
191
+
192
+ The `mixin` method can be used to add the level label to each log message such as in the following example:
193
+ ```js
194
+ const logger = pino({
195
+ mixin(_context, level) {
196
+ return { 'level-label': logger.levels.labels[level] }
197
+ }
198
+ })
199
+
200
+ logger.info({
201
+ description: 'Ok'
202
+ }, 'Message 1')
203
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","description":"Ok","level-label":"info","msg":"Message 1"}
204
+ logger.error('Message 2')
205
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","level-label":"error","msg":"Message 2"}
206
+ ```
207
+
208
+ If the `mixin` feature is being used merely to add static metadata to each log message,
209
+ then a [child logger ⇗](/docs/child-loggers.md) should be used instead. Unless your application
210
+ needs to concatenate values for a specific key multiple times, in which case `mixin` can be
211
+ used to avoid the [duplicate keys caveat](/docs/child-loggers.md#duplicate-keys-caveat):
212
+
213
+ ```js
214
+ const logger = pino({
215
+ mixin (obj, num, logger) {
216
+ return {
217
+ tags: logger.tags
218
+ }
219
+ }
220
+ })
221
+ logger.tags = {}
222
+
223
+ logger.addTag = function (key, value) {
224
+ logger.tags[key] = value
225
+ }
226
+
227
+ function createChild (parent, ...context) {
228
+ const newChild = logger.child(...context)
229
+ newChild.tags = { ...logger.tags }
230
+ newChild.addTag = function (key, value) {
231
+ newChild.tags[key] = value
232
+ }
233
+ return newChild
234
+ }
235
+
236
+ logger.addTag('foo', 1)
237
+ const child = createChild(logger, {})
238
+ child.addTag('bar', 2)
239
+ logger.info('this will only have `foo: 1`')
240
+ child.info('this will have both `foo: 1` and `bar: 2`')
241
+ logger.info('this will still only have `foo: 1`')
242
+ ```
243
+
244
+ As of pino 7.x, when the `mixin` is used with the [`nestedKey` option](#opt-nestedkey),
245
+ the object returned from the `mixin` method will also be nested. Prior versions would mix
246
+ this object into the root.
247
+
248
+ ```js
249
+ const logger = pino({
250
+ nestedKey: 'payload',
251
+ mixin() {
252
+ return { requestId: requestId.currentId() }
253
+ }
254
+ })
255
+
256
+ logger.info({
257
+ description: 'Ok'
258
+ }, 'Message 1')
259
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","payload":{"requestId":"dfe9a9014b","description":"Ok"},"msg":"Message 1"}
260
+ ```
261
+
262
+ <a id="opt-mixin-merge-strategy"></a>
263
+ #### `mixinMergeStrategy` (Function):
264
+
265
+ Default: `undefined`
266
+
267
+ If provided, the `mixinMergeStrategy` function is called each time one of the active
268
+ logging methods is called. The first parameter is the value `mergeObject` or an empty object,
269
+ the second parameter is the value resulting from `mixin()` (* See [`mixin` option](#opt-mixin) or an empty object.
270
+ The function must synchronously return an object.
271
+
272
+ ```js
273
+ // Default strategy, `mergeObject` has priority
274
+ const logger = pino({
275
+ mixin() {
276
+ return { tag: 'docker' }
277
+ },
278
+ // mixinMergeStrategy(mergeObject, mixinObject) {
279
+ // return Object.assign(mixinMeta, mergeObject)
280
+ // }
281
+ })
282
+
283
+ logger.info({
284
+ tag: 'local'
285
+ }, 'Message')
286
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","tag":"local","msg":"Message"}
287
+ ```
288
+
289
+ ```js
290
+ // Custom mutable strategy, `mixin` has priority
291
+ const logger = pino({
292
+ mixin() {
293
+ return { tag: 'k8s' }
294
+ },
295
+ mixinMergeStrategy(mergeObject, mixinObject) {
296
+ return Object.assign(mergeObject, mixinObject)
297
+ }
298
+ })
299
+
300
+ logger.info({
301
+ tag: 'local'
302
+ }, 'Message')
303
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","tag":"k8s","msg":"Message"}
304
+ ```
305
+
306
+ ```js
307
+ // Custom immutable strategy, `mixin` has priority
308
+ const logger = pino({
309
+ mixin() {
310
+ return { tag: 'k8s' }
311
+ },
312
+ mixinMergeStrategy(mergeObject, mixinObject) {
313
+ return Object.assign({}, mergeObject, mixinObject)
314
+ }
315
+ })
316
+
317
+ logger.info({
318
+ tag: 'local'
319
+ }, 'Message')
320
+ // {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","tag":"k8s","msg":"Message"}
321
+ ```
322
+
323
+ <a id="opt-redact"></a>
324
+ #### `redact` (Array | Object):
325
+
326
+ Default: `undefined`
327
+
328
+ As an array, the `redact` option specifies paths that should
329
+ have their values redacted from any log output.
330
+
331
+ Each path must be a string using a syntax that corresponds to JavaScript dot and bracket notation.
332
+
333
+ If an object is supplied, three options can be specified:
334
+ * `paths` (array): Required. An array of paths. See [redaction - Path Syntax ⇗](/docs/redaction.md#paths) for specifics.
335
+ * `censor` (String|Function|Undefined): Optional. When supplied as a String the `censor` option will overwrite keys that are to be redacted. When set to `undefined` the key will be removed entirely from the object.
336
+ The `censor` option may also be a mapping function. The (synchronous) mapping function has the signature `(value, path) => redactedValue` and is called with the unredacted `value` and `path` to the key being redacted, as an array. For example given a redaction path of `a.b.c` the `path` argument would be `['a', 'b', 'c']`. The value returned from the mapping function becomes the applied censor value. Default: `'[Redacted]'`
337
+ value synchronously.
338
+ Default: `'[Redacted]'`
339
+ * `remove` (Boolean): Optional. Instead of censoring the value, remove both the key and the value. Default: `false`
340
+
341
+ **WARNING**: Never allow user input to define redacted paths.
342
+
343
+ * See the [redaction ⇗](/docs/redaction.md) documentation.
344
+ * See [fast-redact#caveat ⇗](https://github.com/davidmarkclements/fast-redact#caveat)
345
+
346
+ <a id=opt-hooks></a>
347
+ #### `hooks` (Object)
348
+
349
+ An object mapping to hook functions. Hook functions allow for customizing
350
+ internal logger operations. Hook functions ***must*** be synchronous functions.
351
+
352
+ <a id="logmethod"></a>
353
+ ##### `logMethod`
354
+
355
+ Allows for manipulating the parameters passed to logger methods. The signature
356
+ for this hook is `logMethod (args, method, level) {}`, where `args` is an array
357
+ of the arguments that were passed to the log method and `method` is the log
358
+ method itself, `level` is the log level itself. This hook ***must*** invoke the
359
+ `method` function by using apply, like so: `method.apply(this, newArgumentsArray)`.
360
+
361
+ For example, Pino expects a binding object to be the first parameter with an
362
+ optional string message as the second parameter. Using this hook the parameters
363
+ can be flipped:
364
+
365
+ ```js
366
+ const hooks = {
367
+ logMethod (inputArgs, method, level) {
368
+ if (inputArgs.length >= 2) {
369
+ const arg1 = inputArgs.shift()
370
+ const arg2 = inputArgs.shift()
371
+ return method.apply(this, [arg2, arg1, ...inputArgs])
372
+ }
373
+ return method.apply(this, inputArgs)
374
+ }
375
+ }
376
+ ```
377
+
378
+
379
+ <a id="streamWrite"></a>
380
+ ##### `streamWrite`
381
+
382
+ Allows for manipulating the _stringified_ JSON log data just before writing to various transports.
383
+
384
+ The method receives the stringified JSON and must return valid stringified JSON.
385
+
386
+ For example:
387
+ ```js
388
+ const hooks = {
389
+ streamWrite (s) {
390
+ return s.replaceAll('sensitive-api-key', 'XXX')
391
+ }
392
+ }
393
+ ```
394
+
395
+ <a id=opt-formatters></a>
396
+ #### `formatters` (Object)
397
+
398
+ An object containing functions for formatting the shape of the log lines.
399
+ These functions should return a JSONifiable object and
400
+ should never throw. These functions allow for full customization of
401
+ the resulting log lines. For example, they can be used to change
402
+ the level key name or to enrich the default metadata.
403
+
404
+ ##### `level`
405
+
406
+ Changes the shape of the log level. The default shape is `{ level: number }`.
407
+ The function takes two arguments, the label of the level (e.g. `'info'`)
408
+ and the numeric value (e.g. `30`).
409
+
410
+ ps: The log level cannot be customized when using multiple transports
411
+
412
+ ```js
413
+ const formatters = {
414
+ level (label, number) {
415
+ return { level: number }
416
+ }
417
+ }
418
+ ```
419
+
420
+ ##### `bindings`
421
+
422
+ Changes the shape of the bindings. The default shape is `{ pid, hostname }`.
423
+ The function takes a single argument, the bindings object, which can be configured
424
+ using the [`base` option](#opt-base). Called once when creating logger.
425
+
426
+ ```js
427
+ const formatters = {
428
+ bindings (bindings) {
429
+ return { pid: bindings.pid, hostname: bindings.hostname }
430
+ }
431
+ }
432
+ ```
433
+
434
+ ##### `log`
435
+
436
+ Changes the shape of the log object. This function will be called every time
437
+ one of the log methods (such as `.info`) is called. All arguments passed to the
438
+ log method, except the message, will be passed to this function. By default, it does
439
+ not change the shape of the log object.
440
+
441
+ ```js
442
+ const formatters = {
443
+ log (object) {
444
+ return object
445
+ }
446
+ }
447
+ ```
448
+
449
+ <a id=opt-serializers></a>
450
+ #### `serializers` (Object)
451
+
452
+ Default: `{err: pino.stdSerializers.err}`
453
+
454
+ An object containing functions for custom serialization of objects.
455
+ These functions should return an JSONifiable object and they
456
+ should never throw. When logging an object, each top-level property
457
+ matching the exact key of a serializer will be serialized using the defined serializer.
458
+
459
+ The serializers are applied when a property in the logged object matches a property
460
+ in the serializers. The only exception is the `err` serializer as it is also applied in case
461
+ the object is an instance of `Error`, e.g. `logger.info(new Error('kaboom'))`.
462
+ See `errorKey` option to change `err` namespace.
463
+
464
+ * See [pino.stdSerializers](#pino-stdserializers)
465
+
466
+ #### `msgPrefix` (String)
467
+
468
+ Default: `undefined`
469
+
470
+ The `msgPrefix` property allows you to specify a prefix for every message of the logger and its children.
471
+
472
+ ```js
473
+ const logger = pino({
474
+ msgPrefix: '[HTTP] '
475
+ })
476
+ logger.info('got new request!')
477
+ // > [HTTP] got new request!
478
+
479
+ const child = logger.child({})
480
+ child.info('User authenticated!')
481
+ // > [HTTP] User authenticated!
482
+ ```
483
+
484
+ <a id=opt-base></a>
485
+ #### `base` (Object)
486
+
487
+ Default: `{pid: process.pid, hostname: os.hostname}`
488
+
489
+ Key-value object added as child logger to each log line.
490
+
491
+ Set to `undefined` to avoid adding `pid`, `hostname` properties to each log.
492
+
493
+ #### `enabled` (Boolean)
494
+
495
+ Default: `true`
496
+
497
+ Set to `false` to disable logging.
498
+
499
+ #### `crlf` (Boolean)
500
+
501
+ Default: `false`
502
+
503
+ Set to `true` to logs newline delimited JSON with `\r\n` instead of `\n`.
504
+
505
+ <a id=opt-timestamp></a>
506
+ #### `timestamp` (Boolean | Function)
507
+
508
+ Default: `true`
509
+
510
+ Enables or disables the inclusion of a timestamp in the
511
+ log message. If a function is supplied, it must synchronously return a partial JSON string
512
+ representation of the time, e.g. `,"time":1493426328206` (which is the default).
513
+
514
+ If set to `false`, no timestamp will be included in the output.
515
+
516
+ See [stdTimeFunctions](#pino-stdtimefunctions) for a set of available functions
517
+ for passing in as a value for this option.
518
+
519
+ Example:
520
+ ```js
521
+ timestamp: () => `,"time":"${new Date(Date.now()).toISOString()}"`
522
+ // which is equivalent to:
523
+ // timestamp: stdTimeFunctions.isoTime
524
+ ```
525
+
526
+ **Caution**: attempting to format time in-process will significantly impact logging performance.
527
+
528
+ <a id=opt-messagekey></a>
529
+ #### `messageKey` (String)
530
+
531
+ Default: `'msg'`
532
+
533
+ The string key for the 'message' in the JSON object.
534
+
535
+ <a id=opt-messagekey></a>
536
+ #### `errorKey` (String)
537
+
538
+ Default: `'err'`
539
+
540
+ The string key for the 'error' in the JSON object.
541
+
542
+ <a id=opt-nestedkey></a>
543
+ #### `nestedKey` (String)
544
+
545
+ Default: `null`
546
+
547
+ If there's a chance that objects being logged have properties that conflict with those from pino itself (`level`, `timestamp`, `pid`, etc)
548
+ and duplicate keys in your log records are undesirable, pino can be configured with a `nestedKey` option that causes any `object`s that are logged
549
+ to be placed under a key whose name is the value of `nestedKey`.
550
+
551
+ This way, when searching something like Kibana for values, one can consistently search under the configured `nestedKey` value instead of the root log record keys.
552
+
553
+ For example,
554
+ ```js
555
+ const logger = require('pino')({
556
+ nestedKey: 'payload'
557
+ })
558
+
559
+ const thing = { level: 'hi', time: 'never', foo: 'bar'} // has pino-conflicting properties!
560
+ logger.info(thing)
561
+
562
+ // logs the following:
563
+ // {"level":30,"time":1578357790020,"pid":91736,"hostname":"x","payload":{"level":"hi","time":"never","foo":"bar"}}
564
+ ```
565
+ In this way, logged objects' properties don't conflict with pino's standard logging properties,
566
+ and searching for logged objects can start from a consistent path.
567
+
568
+ #### `browser` (Object)
569
+
570
+ Browser only, may have `asObject` and `write` keys. This option is separately
571
+ documented in the [Browser API ⇗](/docs/browser.md) documentation.
572
+
573
+ * See [Browser API ⇗](/docs/browser.md)
574
+
575
+ #### `transport` (Object)
576
+
577
+ The `transport` option is a shorthand for the [pino.transport()](#pino-transport) function.
578
+ It supports the same input options:
579
+ ```js
580
+ require('pino')({
581
+ transport: {
582
+ target: '/absolute/path/to/my-transport.mjs'
583
+ }
584
+ })
585
+
586
+ // or multiple transports
587
+ require('pino')({
588
+ transport: {
589
+ targets: [
590
+ { target: '/absolute/path/to/my-transport.mjs', level: 'error' },
591
+ { target: 'some-file-transport', options: { destination: '/dev/null' }
592
+ ]
593
+ }
594
+ })
595
+ ```
596
+
597
+ If the transport option is supplied to `pino`, a [`destination`](#destination) parameter may not also be passed as a separate argument to `pino`:
598
+
599
+ ```js
600
+ pino({ transport: {}}, '/path/to/somewhere') // THIS WILL NOT WORK, DO NOT DO THIS
601
+ pino({ transport: {}}, process.stderr) // THIS WILL NOT WORK, DO NOT DO THIS
602
+ ```
603
+
604
+ when using the `transport` option. In this case, an `Error` will be thrown.
605
+
606
+ * See [pino.transport()](#pino-transport)
607
+
608
+ #### `onChild` (Function)
609
+
610
+ The `onChild` function is a synchronous callback that will be called on each creation of a new child, passing the child instance as its first argument.
611
+ Any error thrown inside the callback will be uncaught and should be handled inside the callback.
612
+ ```js
613
+ const parent = require('pino')({ onChild: (instance) => {
614
+ // Execute call back code for each newly created child.
615
+ }})
616
+ // `onChild` will now be executed with the new child.
617
+ parent.child(bindings)
618
+ ```
619
+
620
+
621
+ <a id="destination"></a>
622
+ ### `destination` (Number | String | Object | DestinationStream | SonicBoomOpts | WritableStream)
623
+
624
+ Default: `pino.destination(1)` (STDOUT)
625
+
626
+ The `destination` parameter can be a file descriptor, a file path, or an
627
+ object with `dest` property pointing to a fd or path.
628
+ An ordinary Node.js `stream` file descriptor can be passed as the
629
+ destination (such as the result
630
+ of `fs.createWriteStream`) but for peak log writing performance, it is strongly
631
+ recommended to use `pino.destination` to create the destination stream.
632
+ Note that the `destination` parameter can be the result of `pino.transport()`.
633
+
634
+ ```js
635
+ // pino.destination(1) by default
636
+ const stdoutLogger = require('pino')()
637
+
638
+ // destination param may be in first position when no options:
639
+ const fileLogger = require('pino')( pino.destination('/log/path'))
640
+
641
+ // use the stderr file handle to log to stderr:
642
+ const opts = {name: 'my-logger'}
643
+ const stderrLogger = require('pino')(opts, pino.destination(2))
644
+
645
+ // automatic wrapping in pino.destination
646
+ const fileLogger = require('pino')('/log/path')
647
+
648
+ // Asynchronous logging
649
+ const fileLogger = pino(pino.destination({ dest: '/log/path', sync: false }))
650
+ ```
651
+
652
+ However, there are some special instances where `pino.destination` is not used as the default:
653
+
654
+ + When something, e.g a process manager, has monkey-patched `process.stdout.write`.
655
+
656
+ In these cases `process.stdout` is used instead.
657
+
658
+ Note: If the parameter is a string integer, e.g. `'1'`, it will be coerced to
659
+ a number and used as a file descriptor. If this is not desired, provide a full
660
+ path, e.g. `/tmp/1`.
661
+
662
+ * See [`pino.destination`](#pino-destination)
663
+
664
+ <a id="metadata"></a>
665
+ #### `destination[Symbol.for('pino.metadata')]`
666
+
667
+ Default: `false`
668
+
669
+ Using the global symbol `Symbol.for('pino.metadata')` as a key on the `destination` parameter and
670
+ setting the key to `true`, indicates that the following properties should be
671
+ set on the `destination` object after each log line is written:
672
+
673
+ * the last logging level as `destination.lastLevel`
674
+ * the last logging message as `destination.lastMsg`
675
+ * the last logging object as `destination.lastObj`
676
+ * the last time as `destination.lastTime`, which will be the partial string returned
677
+ by the time function.
678
+ * the last logger instance as `destination.lastLogger` (to support child
679
+ loggers)
680
+
681
+ The following is a succinct usage example:
682
+
683
+ ```js
684
+ const dest = pino.destination('/dev/null')
685
+ dest[Symbol.for('pino.metadata')] = true
686
+ const logger = pino(dest)
687
+ logger.info({a: 1}, 'hi')
688
+ const { lastMsg, lastLevel, lastObj, lastTime} = dest
689
+ console.log(
690
+ 'Logged message "%s" at level %d with object %o at time %s',
691
+ lastMsg, lastLevel, lastObj, lastTime
692
+ ) // Logged message "hi" at level 30 with object { a: 1 } at time 1531590545089
693
+ ```
694
+
695
+ <a id="logger"></a>
696
+ ## Logger Instance
697
+
698
+ The logger instance is the object returned by the main exported
699
+ [`pino`](#export) function.
700
+
701
+ The primary purpose of the logger instance is to provide logging methods.
702
+
703
+ The default logging methods are `trace`, `debug`, `info`, `warn`, `error`, and `fatal`.
704
+
705
+ Each logging method has the following signature:
706
+ `([mergingObject], [message], [...interpolationValues])`.
707
+
708
+ The parameters are explained below using the `logger.info` method but the same applies to all logging methods.
709
+
710
+ ### Logging Method Parameters
711
+
712
+ <a id=mergingobject></a>
713
+ #### `mergingObject` (Object)
714
+
715
+ An object can optionally be supplied as the first parameter. Each enumerable key and value
716
+ of the `mergingObject` is copied into the JSON log line.
717
+
718
+ ```js
719
+ logger.info({MIX: {IN: true}})
720
+ // {"level":30,"time":1531254555820,"pid":55956,"hostname":"x","MIX":{"IN":true}}
721
+ ```
722
+
723
+ If the object is of type Error, it is wrapped in an object containing a property err (`{ err: mergingObject }`).
724
+ This allows for a unified error handling flow.
725
+
726
+ Options `serializers` and `errorKey` could be used at instantiation time to change the namespace
727
+ from `err` to another string as preferred.
728
+
729
+ <a id="message"></a>
730
+ #### `message` (String)
731
+
732
+ A `message` string can optionally be supplied as the first parameter, or
733
+ as the second parameter after supplying a `mergingObject`.
734
+
735
+ By default, the contents of the `message` parameter will be merged into the
736
+ JSON log line under the `msg` key:
737
+
738
+ ```js
739
+ logger.info('hello world')
740
+ // {"level":30,"time":1531257112193,"msg":"hello world","pid":55956,"hostname":"x"}
741
+ ```
742
+
743
+ The `message` parameter takes precedence over the `mergingObject`.
744
+ That is, if a `mergingObject` contains a `msg` property, and a `message` parameter
745
+ is supplied in addition, the `msg` property in the output log will be the value of
746
+ the `message` parameter not the value of the `msg` property on the `mergingObject`.
747
+ See [Avoid Message Conflict](/docs/help.md#avoid-message-conflict) for information
748
+ on how to overcome this limitation.
749
+
750
+ If no `message` parameter is provided, and the `mergingObject` is of type `Error` or it has a property named `err`, the
751
+ `message` parameter is set to the `message` value of the error. See option `errorKey` if you want to change the namespace.
752
+
753
+ The `messageKey` option can be used at instantiation time to change the namespace
754
+ from `msg` to another string as preferred.
755
+
756
+ The `message` string may contain a printf style string with support for
757
+ the following placeholders:
758
+
759
+ * `%s` – string placeholder
760
+ * `%d` – digit placeholder
761
+ * `%O`, `%o`, and `%j` – object placeholder
762
+
763
+ Values supplied as additional arguments to the logger method will
764
+ then be interpolated accordingly.
765
+
766
+ * See [`messageKey` pino option](#opt-messagekey)
767
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
768
+
769
+ <a id="interpolationvalues"></a>
770
+ #### `...interpolationValues` (Any)
771
+
772
+ All arguments supplied after `message` are serialized and interpolated according
773
+ to any supplied printf-style placeholders (`%s`, `%d`, `%o`|`%O`|`%j`) to form
774
+ the final output `msg` value for the JSON log line.
775
+
776
+ ```js
777
+ logger.info('%o hello %s', {worldly: 1}, 'world')
778
+ // {"level":30,"time":1531257826880,"msg":"{\"worldly\":1} hello world","pid":55956,"hostname":"x"}
779
+ ```
780
+
781
+ Since pino v6, we do not automatically concatenate and cast to string
782
+ consecutive parameters:
783
+
784
+ ```js
785
+ logger.info('hello', 'world')
786
+ // {"level":30,"time":1531257618044,"msg":"hello","pid":55956,"hostname":"x"}
787
+ // world is missing
788
+ ```
789
+
790
+ However, it's possible to inject a hook to modify this behavior:
791
+
792
+ ```js
793
+ const pinoOptions = {
794
+ hooks: { logMethod }
795
+ }
796
+
797
+ function logMethod (args, method) {
798
+ if (args.length === 2) {
799
+ args[0] = `${args[0]} %j`
800
+ }
801
+ method.apply(this, args)
802
+ }
803
+
804
+ const logger = pino(pinoOptions)
805
+ ```
806
+
807
+ * See [`message` log method parameter](#message)
808
+ * See [`logMethod` hook](#logmethod)
809
+
810
+ <a id="error-serialization"></a>
811
+ #### Errors
812
+
813
+ Errors can be supplied as either the first parameter or if already using `mergingObject` then as the `err` property on the `mergingObject`.
814
+
815
+ Options `serializers` and `errorKey` could be used at instantiation time to change the namespace
816
+ from `err` to another string as preferred.
817
+
818
+ > ## Note
819
+ > This section describes the default configuration. The error serializer can be
820
+ > mapped to a different key using the [`serializers`](#opt-serializers) option.
821
+ ```js
822
+ logger.info(new Error("test"))
823
+ // {"level":30,"time":1531257618044,"msg":"test","stack":"...","type":"Error","pid":55956,"hostname":"x"}
824
+
825
+ logger.info({ err: new Error("test"), otherkey: 123 }, "some text")
826
+ // {"level":30,"time":1531257618044,"err":{"msg": "test", "stack":"...","type":"Error"},"msg":"some text","pid":55956,"hostname":"x","otherkey":123}
827
+ ```
828
+
829
+ <a id="trace"></a>
830
+ ### `logger.trace([mergingObject], [message], [...interpolationValues])`
831
+
832
+ Write a `'trace'` level log, if the configured [`level`](#level) allows for it.
833
+
834
+ * See [`mergingObject` log method parameter](#mergingobject)
835
+ * See [`message` log method parameter](#message)
836
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
837
+
838
+ <a id="debug"></a>
839
+ ### `logger.debug([mergingObject], [message], [...interpolationValues])`
840
+
841
+ Write a `'debug'` level log, if the configured `level` allows for it.
842
+
843
+ * See [`mergingObject` log method parameter](#mergingobject)
844
+ * See [`message` log method parameter](#message)
845
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
846
+
847
+ <a id="info"></a>
848
+ ### `logger.info([mergingObject], [message], [...interpolationValues])`
849
+
850
+ Write an `'info'` level log, if the configured `level` allows for it.
851
+
852
+ * See [`mergingObject` log method parameter](#mergingobject)
853
+ * See [`message` log method parameter](#message)
854
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
855
+
856
+ <a id="warn"></a>
857
+ ### `logger.warn([mergingObject], [message], [...interpolationValues])`
858
+
859
+ Write a `'warn'` level log, if the configured `level` allows for it.
860
+
861
+ * See [`mergingObject` log method parameter](#mergingobject)
862
+ * See [`message` log method parameter](#message)
863
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
864
+
865
+ <a id="error"></a>
866
+ ### `logger.error([mergingObject], [message], [...interpolationValues])`
867
+
868
+ Write a `'error'` level log, if the configured `level` allows for it.
869
+
870
+ * See [`mergingObject` log method parameter](#mergingobject)
871
+ * See [`message` log method parameter](#message)
872
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
873
+
874
+ <a id="fatal"></a>
875
+ ### `logger.fatal([mergingObject], [message], [...interpolationValues])`
876
+
877
+ Write a `'fatal'` level log, if the configured `level` allows for it.
878
+
879
+ Since `'fatal'` level messages are intended to be logged just before the process exiting the `fatal`
880
+ method will always sync flush the destination.
881
+ Therefore it's important not to misuse `fatal` since
882
+ it will cause performance overhead if used for any
883
+ other purpose than writing final log messages before
884
+ the process crashes or exits.
885
+
886
+ * See [`mergingObject` log method parameter](#mergingobject)
887
+ * See [`message` log method parameter](#message)
888
+ * See [`...interpolationValues` log method parameter](#interpolationvalues)
889
+
890
+ <a id="silent"><a>
891
+ ### `logger.silent()`
892
+
893
+ Noop function.
894
+
895
+ <a id="child"></a>
896
+ ### `logger.child(bindings, [options]) => logger`
897
+
898
+ The `logger.child` method allows for the creation of stateful loggers,
899
+ where key-value pairs can be pinned to a logger causing them to be output
900
+ on every log line.
901
+
902
+ Child loggers use the same output stream as the parent and inherit
903
+ the current log level of the parent at the time they are spawned.
904
+
905
+ The log level of a child is mutable. It can be set independently
906
+ of the parent either by setting the [`level`](#level) accessor after creating
907
+ the child logger or using the [`options.level`](#optionslevel-string) key.
908
+
909
+ <a id="logger-child-bindings"></a>
910
+ #### `bindings` (Object)
911
+
912
+ An object of key-value pairs to include in every log line output
913
+ via the returned child logger.
914
+
915
+ ```js
916
+ const child = logger.child({ MIX: {IN: 'always'} })
917
+ child.info('hello')
918
+ // {"level":30,"time":1531258616689,"msg":"hello","pid":64849,"hostname":"x","MIX":{"IN":"always"}}
919
+ child.info('child!')
920
+ // {"level":30,"time":1531258617401,"msg":"child!","pid":64849,"hostname":"x","MIX":{"IN":"always"}}
921
+ ```
922
+
923
+ The `bindings` object may contain any key except for reserved configuration keys `level` and `serializers`.
924
+
925
+ ##### `bindings.serializers` (Object) - DEPRECATED
926
+
927
+ Use `options.serializers` instead.
928
+
929
+ #### `options` (Object)
930
+
931
+ Options for child logger. These options will override the parent logger options.
932
+
933
+ ##### `options.level` (String)
934
+
935
+ The `level` property overrides the log level of the child logger.
936
+ By default, the parent log level is inherited.
937
+ After the creation of the child logger, it is also accessible using the [`logger.level`](#logger-level) key.
938
+
939
+ ```js
940
+ const logger = pino()
941
+ logger.debug('nope') // will not log, since default level is info
942
+ const child = logger.child({foo: 'bar'}, {level: 'debug'})
943
+ child.debug('debug!') // will log as the `level` property set the level to debug
944
+ ```
945
+
946
+ ##### `options.msgPrefix` (String)
947
+
948
+ Default: `undefined`
949
+
950
+ The `msgPrefix` property allows you to specify a prefix for every message of the child logger.
951
+ By default, the parent prefix is inherited.
952
+ If the parent already has a prefix, the prefix of the parent and then the child will be displayed.
953
+
954
+ ```js
955
+ const logger = pino({
956
+ msgPrefix: '[HTTP] '
957
+ })
958
+ logger.info('got new request!')
959
+ // > [HTTP] got new request!
960
+
961
+ const child = logger.child({avengers: 'assemble'}, {msgPrefix: '[Proxy] '})
962
+ child.info('message proxied!')
963
+ // > [HTTP] [Proxy] message proxied!
964
+ ```
965
+
966
+ ##### `options.redact` (Array | Object)
967
+
968
+ Setting `options.redact` to an array or object will override the parent `redact` options. To remove `redact` options inherited from the parent logger set this value as an empty array (`[]`).
969
+
970
+ ```js
971
+ const logger = require('pino')({ redact: ['hello'] })
972
+ logger.info({ hello: 'world' })
973
+ // {"level":30,"time":1625794363403,"pid":67930,"hostname":"x","hello":"[Redacted]"}
974
+ const child = logger.child({ foo: 'bar' }, { redact: ['foo'] })
975
+ logger.info({ hello: 'world' })
976
+ // {"level":30,"time":1625794553558,"pid":67930,"hostname":"x","hello":"world", "foo": "[Redacted]" }
977
+ ```
978
+
979
+ * See [`redact` option](#opt-redact)
980
+
981
+ ##### `options.serializers` (Object)
982
+
983
+ Child loggers inherit the [serializers](#opt-serializers) from the parent logger.
984
+
985
+ Setting the `serializers` key of the `options` object will override
986
+ any configured parent serializers.
987
+
988
+ ```js
989
+ const logger = require('pino')()
990
+ logger.info({test: 'will appear'})
991
+ // {"level":30,"time":1531259759482,"pid":67930,"hostname":"x","test":"will appear"}
992
+ const child = logger.child({}, {serializers: {test: () => `child-only serializer`}})
993
+ child.info({test: 'will be overwritten'})
994
+ // {"level":30,"time":1531259784008,"pid":67930,"hostname":"x","test":"child-only serializer"}
995
+ ```
996
+
997
+ * See [`serializers` option](#opt-serializers)
998
+ * See [pino.stdSerializers](#pino-stdSerializers)
999
+
1000
+ <a id="logger-bindings"></a>
1001
+ ### `logger.bindings()`
1002
+
1003
+ Returns an object containing all the current bindings, cloned from the ones passed in via `logger.child()`.
1004
+ ```js
1005
+ const child = logger.child({ foo: 'bar' })
1006
+ console.log(child.bindings())
1007
+ // { foo: 'bar' }
1008
+ const anotherChild = child.child({ MIX: { IN: 'always' } })
1009
+ console.log(anotherChild.bindings())
1010
+ // { foo: 'bar', MIX: { IN: 'always' } }
1011
+ ```
1012
+
1013
+ <a id="logger-set-bindings"></a>
1014
+ ### `logger.setBindings(bindings)`
1015
+
1016
+ Adds to the bindings of this logger instance.
1017
+
1018
+ **Note:** Does not overwrite bindings. Can potentially result in duplicate keys in
1019
+ log lines.
1020
+
1021
+ * See [`bindings` parameter in `logger.child`](#logger-child-bindings)
1022
+
1023
+ <a id="flush"></a>
1024
+ ### `logger.flush([cb])`
1025
+
1026
+ Flushes the content of the buffer when using `pino.destination({
1027
+ sync: false })`.
1028
+
1029
+ This is an asynchronous, best used as fire and forget, operation.
1030
+
1031
+ The use case is primarily for asynchronous logging, which may buffer
1032
+ log lines while others are being written. The `logger.flush` method can be
1033
+ used to flush the logs
1034
+ on a long interval, say ten seconds. Such a strategy can provide an
1035
+ optimum balance between extremely efficient logging at high demand periods
1036
+ and safer logging at low demand periods.
1037
+
1038
+ If there is a need to wait for the logs to be flushed, a callback should be used.
1039
+
1040
+ * See [`destination` parameter](#destination)
1041
+ * See [Asynchronous Logging ⇗](/docs/asynchronous.md)
1042
+
1043
+ <a id="logger-level"></a>
1044
+ ### `logger.level` (String) [Getter/Setter]
1045
+
1046
+ Set this property to the desired logging level.
1047
+
1048
+ The core levels and their values are as follows:
1049
+
1050
+ | | | | | | | | |
1051
+ |:-----------|-------|-------|------|------|-------|-------|---------:|
1052
+ | **Level:** | trace | debug | info | warn | error | fatal | silent |
1053
+ | **Value:** | 10 | 20 | 30 | 40 | 50 | 60 | Infinity |
1054
+
1055
+ The logging level is a *minimum* level based on the associated value of that level.
1056
+
1057
+ For instance if `logger.level` is `info` *(30)* then `info` *(30)*, `warn` *(40)*, `error` *(50)*, and `fatal` *(60)* log methods will be enabled but the `trace` *(10)* and `debug` *(20)* methods, being less than 30, will not.
1058
+
1059
+ The `silent` logging level is a specialized level that will disable all logging,
1060
+ the `silent` log method is a noop function.
1061
+
1062
+ <a id="islevelenabled"></a>
1063
+ ### `logger.isLevelEnabled(level)`
1064
+
1065
+ A utility method for determining if a given log level will write to the destination.
1066
+
1067
+ #### `level` (String)
1068
+
1069
+ The given level to check against:
1070
+
1071
+ ```js
1072
+ if (logger.isLevelEnabled('debug')) logger.debug('conditional log')
1073
+ ```
1074
+
1075
+ #### `levelLabel` (String)
1076
+
1077
+ Defines the method name of the new level.
1078
+
1079
+ * See [`logger.level`](#level)
1080
+
1081
+ #### `levelValue` (Number)
1082
+
1083
+ Defines the associated minimum threshold value for the level, and
1084
+ therefore where it sits in order of priority among other levels.
1085
+
1086
+ * See [`logger.level`](#level)
1087
+
1088
+ <a id="levelVal"></a>
1089
+ ### `logger.levelVal` (Number)
1090
+
1091
+ Supplies the integer value for the current logging level.
1092
+
1093
+ ```js
1094
+ if (logger.levelVal === 30) {
1095
+ console.log('logger level is `info`')
1096
+ }
1097
+ ```
1098
+
1099
+ <a id="levels"></a>
1100
+ ### `logger.levels` (Object)
1101
+
1102
+ Levels are mapped to values to determine the minimum threshold that a
1103
+ logging method should be enabled at (see [`logger.level`](#level)).
1104
+
1105
+ The `logger.levels` property holds the mappings between levels and values,
1106
+ and vice versa.
1107
+
1108
+ ```sh
1109
+ $ node -p "require('pino')().levels"
1110
+ ```
1111
+
1112
+ ```js
1113
+ { labels:
1114
+ { '10': 'trace',
1115
+ '20': 'debug',
1116
+ '30': 'info',
1117
+ '40': 'warn',
1118
+ '50': 'error',
1119
+ '60': 'fatal' },
1120
+ values:
1121
+ { fatal: 60, error: 50, warn: 40, info: 30, debug: 20, trace: 10 } }
1122
+ ```
1123
+
1124
+ * See [`logger.level`](#level)
1125
+
1126
+ <a id="serializers"></a>
1127
+ ### logger\[Symbol.for('pino.serializers')\]
1128
+
1129
+ Returns the serializers as applied to the current logger instance. If a child logger did not
1130
+ register its own serializer upon instantiation the serializers of the parent will be returned.
1131
+
1132
+ <a id="level-change"></a>
1133
+ ### Event: 'level-change'
1134
+
1135
+ The logger instance is also an [`EventEmitter ⇗`](https://nodejs.org/dist/latest/docs/api/events.html#events_class_eventemitter)
1136
+
1137
+ A listener function can be attached to a logger via the `level-change` event
1138
+
1139
+ The listener is passed five arguments:
1140
+
1141
+ * `levelLabel` – the new level string, e.g `trace`
1142
+ * `levelValue` – the new level number, e.g `10`
1143
+ * `previousLevelLabel` – the prior level string, e.g `info`
1144
+ * `previousLevelValue` – the prior level number, e.g `30`
1145
+ * `logger` – the logger instance from which the event originated
1146
+
1147
+ ```js
1148
+ const logger = require('pino')()
1149
+ logger.on('level-change', (lvl, val, prevLvl, prevVal) => {
1150
+ console.log('%s (%d) was changed to %s (%d)', prevLvl, prevVal, lvl, val)
1151
+ })
1152
+ logger.level = 'trace' // trigger event
1153
+ ```
1154
+
1155
+ Please note that due to a [known bug](https://github.com/pinojs/pino/issues/1006), every `logger.child()` call will
1156
+ fire a `level-change` event. These events can be ignored by writing an event handler like:
1157
+
1158
+ ```js
1159
+ const logger = require('pino')()
1160
+ logger.on('level-change', function (lvl, val, prevLvl, prevVal, instance) {
1161
+ if (logger !== instance) {
1162
+ return
1163
+ }
1164
+ console.log('%s (%d) was changed to %s (%d)', prevLvl, prevVal, lvl, val)
1165
+ })
1166
+ logger.child({}); // trigger an event by creating a child instance, notice no console.log
1167
+ logger.level = 'trace' // trigger event using actual value change, notice console.log
1168
+ ```
1169
+
1170
+ <a id="version"></a>
1171
+ ### `logger.version` (String)
1172
+
1173
+ Exposes the Pino package version. Also available on the exported `pino` function.
1174
+
1175
+ * See [`pino.version`](#pino-version)
1176
+
1177
+ ## Statics
1178
+
1179
+ <a id="pino-destination"></a>
1180
+ ### `pino.destination([opts]) => SonicBoom`
1181
+
1182
+ Create a Pino Destination instance: a stream-like object with
1183
+ significantly more throughput than a standard Node.js stream.
1184
+
1185
+ ```js
1186
+ const pino = require('pino')
1187
+ const logger = pino(pino.destination('./my-file'))
1188
+ const logger2 = pino(pino.destination())
1189
+ const logger3 = pino(pino.destination({
1190
+ dest: './my-file',
1191
+ minLength: 4096, // Buffer before writing
1192
+ sync: false // Asynchronous logging, the default
1193
+ }))
1194
+ const logger4 = pino(pino.destination({
1195
+ dest: './my-file2',
1196
+ sync: true // Synchronous logging
1197
+ }))
1198
+ ```
1199
+
1200
+ The `pino.destination` method may be passed a file path or a numerical file descriptor.
1201
+ By default, `pino.destination` will use `process.stdout.fd` (1) as the file descriptor.
1202
+
1203
+ `pino.destination` is implemented on [`sonic-boom` ⇗](https://github.com/mcollina/sonic-boom).
1204
+
1205
+ A `pino.destination` instance can also be used to reopen closed files
1206
+ (for example, for some log rotation scenarios), see [Reopening log files](/docs/help.md#reopening).
1207
+
1208
+ * See [`destination` parameter](#destination)
1209
+ * See [`sonic-boom` ⇗](https://github.com/mcollina/sonic-boom)
1210
+ * See [Reopening log files](/docs/help.md#reopening)
1211
+ * See [Asynchronous Logging ⇗](/docs/asynchronous.md)
1212
+
1213
+ <a id="pino-transport"></a>
1214
+ ### `pino.transport(options) => ThreadStream`
1215
+
1216
+ Create a stream that routes logs to a worker thread that
1217
+ wraps around a [Pino Transport](/docs/transports.md).
1218
+
1219
+ ```js
1220
+ const pino = require('pino')
1221
+ const transport = pino.transport({
1222
+ target: 'some-transport',
1223
+ options: { some: 'options for', the: 'transport' }
1224
+ })
1225
+ pino(transport)
1226
+ ```
1227
+
1228
+ Multiple transports may also be defined, and specific levels can be logged to each transport:
1229
+
1230
+ ```js
1231
+ const pino = require('pino')
1232
+ const transport = pino.transport({
1233
+ targets: [{
1234
+ level: 'info',
1235
+ target: 'pino-pretty' // must be installed separately
1236
+ }, {
1237
+ level: 'trace',
1238
+ target: 'pino/file',
1239
+ options: { destination: '/path/to/store/logs' }
1240
+ }]
1241
+ })
1242
+ pino(transport)
1243
+ ```
1244
+
1245
+ A pipeline could also be created to transform log lines _before_ sending them:
1246
+
1247
+ ```js
1248
+ const pino = require('pino')
1249
+ const transport = pino.transport({
1250
+ pipeline: [{
1251
+ target: 'pino-syslog' // must be installed separately
1252
+ }, {
1253
+ target: 'pino-socket' // must be installed separately
1254
+ }]
1255
+ })
1256
+ pino(transport)
1257
+ ```
1258
+
1259
+ Multiple transports can now be defined to include pipelines:
1260
+
1261
+ ```js
1262
+ const pino = require('pino')
1263
+ const transport = pino.transport({
1264
+ targets: [{
1265
+ level: 'info',
1266
+ target: 'pino-pretty' // must be installed separately
1267
+ }, {
1268
+ level: 'trace',
1269
+ target: 'pino/file',
1270
+ options: { destination: '/path/to/store/logs' }
1271
+ }, {
1272
+ pipeline: [{
1273
+ target: 'pino-syslog' // must be installed separately
1274
+ }, {
1275
+ target: 'pino-socket' // must be installed separately
1276
+ }]
1277
+ }
1278
+ ]
1279
+ })
1280
+ pino(transport)
1281
+ ```
1282
+
1283
+ If `WeakRef`, `WeakMap`, and `FinalizationRegistry` are available in the current runtime (v14.5.0+), then the thread
1284
+ will be automatically terminated in case the stream or logger goes out of scope.
1285
+ The `transport()` function adds a listener to `process.on('beforeExit')` and `process.on('exit')` to ensure the worker
1286
+ is flushed and all data synced before the process exits.
1287
+
1288
+ Note that calling `process.exit()` on the main thread will stop the event loop on the main thread from turning. As a result,
1289
+ using `console.log` and `process.stdout` after the main thread called `process.exit()` will not produce any output.
1290
+
1291
+ If you are embedding/integrating pino within your framework, you will need to make pino aware of the script that is calling it,
1292
+ like so:
1293
+
1294
+ ```js
1295
+ const pino = require('pino')
1296
+ const getCaller = require('get-caller-file')
1297
+
1298
+ module.exports = function build () {
1299
+ const logger = pino({
1300
+ transport: {
1301
+ caller: getCaller(),
1302
+ target: 'transport',
1303
+ options: { destination: './destination' }
1304
+ }
1305
+ })
1306
+ return logger
1307
+ }
1308
+ ```
1309
+
1310
+ For more on transports, how they work, and how to create them see the [`Transports documentation`](/docs/transports.md).
1311
+
1312
+ * See [`Transports`](/docs/transports.md)
1313
+ * See [`thread-stream` ⇗](https://github.com/mcollina/thread-stream)
1314
+
1315
+ #### Options
1316
+
1317
+ * `target`: The transport to pass logs through. This may be an installed module name or an absolute path.
1318
+ * `options`: An options object which is serialized (see [Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)), passed to the worker thread, parsed and then passed to the exported transport function.
1319
+ * `worker`: [Worker thread](https://nodejs.org/api/worker_threads.html#worker_threads_new_worker_filename_options) configuration options. Additionally, the `worker` option supports `worker.autoEnd`. If this is set to `false` logs will not be flushed on process exit. It is then up to the developer to call `transport.end()` to flush logs.
1320
+ * `targets`: May be specified instead of `target`. Must be an array of transport configurations and/or pipelines. Transport configurations include the aforementioned `options` and `target` options plus a `level` option which will send only logs above a specified level to a transport.
1321
+ * `pipeline`: May be specified instead of `target`. Must be an array of transport configurations. Transport configurations include the aforementioned `options` and `target` options. All intermediate steps in the pipeline _must_ be `Transform` streams and not `Writable`.
1322
+ * `dedupe`: See [pino.multistream options](#pino-multistream)
1323
+
1324
+ <a id="pino-multistream"></a>
1325
+
1326
+ ### `pino.multistream(streamsArray, opts) => MultiStreamRes`
1327
+
1328
+ Create a stream composed by multiple destination streams and returns an
1329
+ object implementing the [MultiStreamRes](#multistreamres) interface.
1330
+
1331
+ ```js
1332
+ var fs = require('node:fs')
1333
+ var pino = require('pino')
1334
+ var pretty = require('pino-pretty')
1335
+ var streams = [
1336
+ {stream: fs.createWriteStream('/tmp/info.stream.out')},
1337
+ {stream: pretty() },
1338
+ {level: 'debug', stream: fs.createWriteStream('/tmp/debug.stream.out')},
1339
+ {level: 'fatal', stream: fs.createWriteStream('/tmp/fatal.stream.out')}
1340
+ ]
1341
+
1342
+ var log = pino({
1343
+ level: 'debug' // this MUST be set at the lowest level of the
1344
+ // destinations
1345
+ }, pino.multistream(streams))
1346
+
1347
+ log.debug('this will be written to /tmp/debug.stream.out')
1348
+ log.info('this will be written to /tmp/debug.stream.out and /tmp/info.stream.out')
1349
+ log.fatal('this will be written to /tmp/debug.stream.out, /tmp/info.stream.out and /tmp/fatal.stream.out')
1350
+ ```
1351
+
1352
+ In order for `multistream` to work, the log level __must__ be set to the lowest level used in the streams array. Default is `info`.
1353
+
1354
+ #### Options
1355
+
1356
+ * `levels`: Pass custom log level definitions to the instance as an object.
1357
+
1358
+ + `dedupe`: Set this to `true` to send logs only to the stream with the higher level. Default: `false`
1359
+
1360
+ `dedupe` flag can be useful for example when using `pino.multistream` to redirect `error` logs to `process.stderr` and others to `process.stdout`:
1361
+
1362
+ ```js
1363
+ var pino = require('pino')
1364
+ var multistream = pino.multistream
1365
+ var streams = [
1366
+ {level: 'debug', stream: process.stdout},
1367
+ {level: 'error', stream: process.stderr},
1368
+ ]
1369
+
1370
+ var opts = {
1371
+ levels: {
1372
+ silent: Infinity,
1373
+ fatal: 60,
1374
+ error: 50,
1375
+ warn: 50,
1376
+ info: 30,
1377
+ debug: 20,
1378
+ trace: 10
1379
+ },
1380
+ dedupe: true,
1381
+ }
1382
+
1383
+ var log = pino({
1384
+ level: 'debug' // this MUST be set at the lowest level of the
1385
+ // destinations
1386
+ }, multistream(streams, opts))
1387
+
1388
+ log.debug('this will be written ONLY to process.stdout')
1389
+ log.info('this will be written ONLY to process.stdout')
1390
+ log.error('this will be written ONLY to process.stderr')
1391
+ log.fatal('this will be written ONLY to process.stderr')
1392
+ ```
1393
+
1394
+ <a id="pino-stdserializers"></a>
1395
+ ### `pino.stdSerializers` (Object)
1396
+
1397
+ The `pino.stdSerializers` object provides functions for serializing objects common to many projects. The standard serializers are directly imported from [pino-std-serializers](https://github.com/pinojs/pino-std-serializers).
1398
+
1399
+ * See [pino-std-serializers ⇗](https://github.com/pinojs/pino-std-serializers)
1400
+
1401
+ <a id="pino-stdtimefunctions"></a>
1402
+ ### `pino.stdTimeFunctions` (Object)
1403
+
1404
+ The [`timestamp`](#opt-timestamp) option can accept a function that determines the
1405
+ `timestamp` value in a log line.
1406
+
1407
+ The `pino.stdTimeFunctions` object provides a very small set of common functions for generating the
1408
+ `timestamp` property. These consist of the following
1409
+
1410
+ * `pino.stdTimeFunctions.epochTime`: Milliseconds since Unix epoch (Default)
1411
+ * `pino.stdTimeFunctions.unixTime`: Seconds since Unix epoch
1412
+ * `pino.stdTimeFunctions.nullTime`: Clears timestamp property (Used when `timestamp: false`)
1413
+ * `pino.stdTimeFunctions.isoTime`: ISO 8601-formatted time in UTC
1414
+
1415
+ * See [`timestamp` option](#opt-timestamp)
1416
+
1417
+ <a id="pino-symbols"></a>
1418
+ ### `pino.symbols` (Object)
1419
+
1420
+ For integration purposes with ecosystem and third-party libraries `pino.symbols`
1421
+ exposes the symbols used to hold non-public state and methods on the logger instance.
1422
+
1423
+ Access to the symbols allows logger state to be adjusted, and methods to be overridden or
1424
+ proxied for performant integration where necessary.
1425
+
1426
+ The `pino.symbols` object is intended for library implementers and shouldn't be utilized
1427
+ for general use.
1428
+
1429
+ <a id="pino-version"></a>
1430
+ ### `pino.version` (String)
1431
+
1432
+ Exposes the Pino package version. Also available on the logger instance.
1433
+
1434
+ * See [`logger.version`](#version)
1435
+
1436
+ ## Interfaces
1437
+ <a id="pino-multistreamres"></a>
1438
+
1439
+ ### `MultiStreamRes`
1440
+ Properties:
1441
+
1442
+ * `write(data)`
1443
+ - `data` Object | string
1444
+ - Returns: void
1445
+
1446
+ Write `data` onto the streams held by the current instance.
1447
+ * `add(dest)`
1448
+ - `dest` [StreamEntry](#streamentry) | [DestinationStream](#destinationstream)
1449
+ - Returns: [MultiStreamRes](#multistreamres)
1450
+
1451
+ Add `dest` stream to the array of streams of the current instance.
1452
+ * `flushSync()`
1453
+ - Returns: `undefined`
1454
+
1455
+ Call `flushSync` on each stream held by the current instance.
1456
+ * `minLevel`
1457
+ - number
1458
+
1459
+ The minimum level amongst all the streams held by the current instance.
1460
+ * `streams`
1461
+ - Returns: [StreamEntry[]](#streamentry)
1462
+
1463
+ The array of streams currently held by the current instance.
1464
+ * `clone(level)`
1465
+ - `level` [Level](#level-1)
1466
+ - Returns: [MultiStreamRes](#multistreamres)
1467
+
1468
+ Returns a cloned object of the current instance but with the provided `level`.
1469
+
1470
+ ### `StreamEntry`
1471
+ Properties:
1472
+
1473
+ * `stream`
1474
+ - DestinationStream
1475
+ * `level`
1476
+ - Optional: [Level](#level-1)
1477
+
1478
+ ### `DestinationStream`
1479
+ Properties:
1480
+
1481
+ * `write(msg)`
1482
+ - `msg` string
1483
+
1484
+ ## Types
1485
+ ### `Level`
1486
+
1487
+ * Values: `"fatal"` | `"error"` | `"warn"` | `"info"` | `"debug"` | `"trace"`