CoolFace
Apppublic

strong-tie/inbound-calls

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
api.md1488 linesDownload Raw Back to docs
1# API2 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 43The exported `pino` function takes two optional arguments,44[`options`](#options) and [`destination`](#destination), and45returns a [logger instance](#logger).46 47<a id=options></a>48### `options` (Object)49 50#### `name` (String)51 52Default: `undefined`53 54The name of the logger. When set adds a `name` field to every JSON line logged.55 56#### `level` (String)57 58Default: `'info'`59 60The 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 62One of `'fatal'`, `'error'`, `'warn'`, `'info'`, `'debug'`, `'trace'` or `'silent'`.63 64Additional 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 72Default: `ASC`73 74Use this option to customize levels order.75In 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```js78const logger = pino({79  levelComparison: 'DESC',80  customLevels: {81    foo: 20, // `foo` is more valuable than `bar`82    bar: 1083  },84})85 86// OR87 88const logger = pino({89  levelComparison: function(current, expected) {90    return current >= expected;91  }92})93```94 95#### `customLevels` (Object)96 97Default: `undefined`98 99Use this option to define additional logging levels.100The keys of the object correspond to the namespace of the log level,101and the values should be the numerical value of the level.102 103```js104const logger = pino({105  customLevels: {106    foo: 35107  }108})109logger.foo('hi')110```111 112<a id=opt-useOnlyCustomLevels></a>113#### `useOnlyCustomLevels` (Boolean)114 115Default: `false`116 117Use this option to only use defined `customLevels` and omit Pino's levels.118Logger's default `level` must be changed to a value in `customLevels` to use `useOnlyCustomLevels`119Warning: this option may not be supported by downstream transports.120 121```js122const logger = pino({123  customLevels: {124    foo: 35125  },126  useOnlyCustomLevels: true,127  level: 'foo'128})129logger.foo('hi')130logger.info('hello') // Will throw an error saying info is not found in logger object131```132#### `depthLimit` (Number)133 134Default: `5`135 136Option to limit stringification at a specific nesting depth when logging circular objects.137 138#### `edgeLimit` (Number)139 140Default: `100`141 142Option 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 147Default: `undefined`148 149If provided, the `mixin` function is called each time one of the active150logging methods is called. The first parameter is the value `mergeObject` or an empty object. The second parameter is the log level number.151The third parameter is the logger or child logger itself, which can be used to152retrieve logger-specific context from within the `mixin` function.153The function must synchronously return an object. The properties of the returned object will be added to the154logged JSON.155 156```js157let n = 0158const logger = pino({159  mixin () {160    return { line: ++n }161  }162})163logger.info('hello')164// {"level":30,"time":1573664685466,"pid":78742,"hostname":"x","line":1,"msg":"hello"}165logger.info('world')166// {"level":30,"time":1573664685469,"pid":78742,"hostname":"x","line":2,"msg":"world"}167```168 169The result of `mixin()` is supposed to be a _new_ object. For performance reason, the object returned by `mixin()` will be mutated by pino.170In 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```js173const mixin = {174    appName: 'My app'175}176 177const logger = pino({178    mixin() {179        return mixin;180    }181})182 183logger.info({184    description: 'Ok'185}, 'Message 1')186// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","appName":"My app","description":"Ok","msg":"Message 1"}187logger.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 192The `mixin` method can be used to add the level label to each log message such as in the following example:193```js194const logger = pino({195  mixin(_context, level) {196    return { 'level-label': logger.levels.labels[level] }197  }198})199 200logger.info({201    description: 'Ok'202}, 'Message 1')203// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","description":"Ok","level-label":"info","msg":"Message 1"}204logger.error('Message 2')205// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","level-label":"error","msg":"Message 2"}206```207 208If the `mixin` feature is being used merely to add static metadata to each log message,209then a [child logger ⇗](/docs/child-loggers.md) should be used instead. Unless your application210needs to concatenate values for a specific key multiple times, in which case `mixin` can be211used to avoid the [duplicate keys caveat](/docs/child-loggers.md#duplicate-keys-caveat):212 213```js214const logger = pino({215  mixin (obj, num, logger) {216    return {217      tags: logger.tags218    }219  }220})221logger.tags = {}222 223logger.addTag = function (key, value) {224  logger.tags[key] = value225}226 227function createChild (parent, ...context) {228  const newChild = logger.child(...context)229  newChild.tags = { ...logger.tags }230  newChild.addTag = function (key, value) {231    newChild.tags[key] = value232  }233  return newChild234}235 236logger.addTag('foo', 1)237const child = createChild(logger, {})238child.addTag('bar', 2)239logger.info('this will only have `foo: 1`')240child.info('this will have both `foo: 1` and `bar: 2`')241logger.info('this will still only have `foo: 1`')242```243 244As of pino 7.x, when the `mixin` is used with the [`nestedKey` option](#opt-nestedkey),245the object returned from the `mixin` method will also be nested. Prior versions would mix246this object into the root.247 248```js249const logger = pino({250    nestedKey: 'payload',251    mixin() {252        return { requestId: requestId.currentId() }253    }254})255 256logger.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 265Default: `undefined`266 267If provided, the `mixinMergeStrategy` function is called each time one of the active268logging methods is called. The first parameter is the value `mergeObject` or an empty object,269the second parameter is the value resulting from `mixin()` (* See [`mixin` option](#opt-mixin) or an empty object.270The function must synchronously return an object.271 272```js273// Default strategy, `mergeObject` has priority274const logger = pino({275    mixin() {276        return { tag: 'docker' }277    },278    // mixinMergeStrategy(mergeObject, mixinObject) {279    //     return Object.assign(mixinMeta, mergeObject)280    // }281})282 283logger.info({284  tag: 'local'285}, 'Message')286// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","tag":"local","msg":"Message"}287```288 289```js290// Custom mutable strategy, `mixin` has priority291const logger = pino({292    mixin() {293        return { tag: 'k8s' }294    },295    mixinMergeStrategy(mergeObject, mixinObject) {296        return Object.assign(mergeObject, mixinObject)297    }298})299 300logger.info({301    tag: 'local'302}, 'Message')303// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","tag":"k8s","msg":"Message"}304```305 306```js307// Custom immutable strategy, `mixin` has priority308const logger = pino({309    mixin() {310        return { tag: 'k8s' }311    },312    mixinMergeStrategy(mergeObject, mixinObject) {313        return Object.assign({}, mergeObject, mixinObject)314    }315})316 317logger.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 326Default: `undefined`327 328As an array, the `redact` option specifies paths that should329have their values redacted from any log output.330 331Each path must be a string using a syntax that corresponds to JavaScript dot and bracket notation.332 333If 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 349An object mapping to hook functions. Hook functions allow for customizing350internal logger operations. Hook functions ***must*** be synchronous functions.351 352<a id="logmethod"></a>353##### `logMethod`354 355Allows for manipulating the parameters passed to logger methods. The signature356for this hook is `logMethod (args, method, level) {}`, where `args` is an array357of the arguments that were passed to the log method and `method` is the log358method itself, `level` is the log level itself. This hook ***must*** invoke the359`method` function by using apply, like so: `method.apply(this, newArgumentsArray)`.360 361For example, Pino expects a binding object to be the first parameter with an362optional string message as the second parameter. Using this hook the parameters363can be flipped:364 365```js366const 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 382Allows for manipulating the _stringified_ JSON log data just before writing to various transports.383 384The method receives the stringified JSON and must return valid stringified JSON.385 386For example:387```js388const 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 398An object containing functions for formatting the shape of the log lines.399These functions should return a JSONifiable object and400should never throw. These functions allow for full customization of401the resulting log lines. For example, they can be used to change402the level key name or to enrich the default metadata.403 404##### `level`405 406Changes the shape of the log level. The default shape is `{ level: number }`.407The function takes two arguments, the label of the level (e.g. `'info'`)408and the numeric value (e.g. `30`).409 410ps: The log level cannot be customized when using multiple transports411 412```js413const formatters = {414  level (label, number) {415    return { level: number }416  }417}418```419 420##### `bindings`421 422Changes the shape of the bindings. The default shape is `{ pid, hostname }`.423The function takes a single argument, the bindings object, which can be configured424using the [`base` option](#opt-base). Called once when creating logger.425 426```js427const formatters = {428  bindings (bindings) {429    return { pid: bindings.pid, hostname: bindings.hostname }430  }431}432```433 434##### `log`435 436Changes the shape of the log object. This function will be called every time437one of the log methods (such as `.info`) is called. All arguments passed to the438log method, except the message, will be passed to this function. By default, it does439not change the shape of the log object.440 441```js442const formatters = {443  log (object) {444    return object445  }446}447```448 449<a id=opt-serializers></a>450#### `serializers` (Object)451 452Default: `{err: pino.stdSerializers.err}`453 454An object containing functions for custom serialization of objects.455These functions should return an JSONifiable object and they456should never throw. When logging an object, each top-level property457matching the exact key of a serializer will be serialized using the defined serializer.458 459The serializers are applied when a property in the logged object matches a property460in the serializers. The only exception is the `err` serializer as it is also applied in case461the object is an instance of `Error`, e.g. `logger.info(new Error('kaboom'))`.462See `errorKey` option to change `err` namespace.463 464* See [pino.stdSerializers](#pino-stdserializers)465 466#### `msgPrefix` (String)467 468Default: `undefined`469 470The `msgPrefix` property allows you to specify a prefix for every message of the logger and its children.471 472```js473const logger = pino({474  msgPrefix: '[HTTP] '475})476logger.info('got new request!')477// >  [HTTP] got new request!478 479const child = logger.child({})480child.info('User authenticated!')481// >  [HTTP] User authenticated!482```483 484<a id=opt-base></a>485#### `base` (Object)486 487Default: `{pid: process.pid, hostname: os.hostname}`488 489Key-value object added as child logger to each log line.490 491Set to `undefined` to avoid adding `pid`, `hostname` properties to each log.492 493#### `enabled` (Boolean)494 495Default: `true`496 497Set to `false` to disable logging.498 499#### `crlf` (Boolean)500 501Default: `false`502 503Set 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 508Default: `true`509 510Enables or disables the inclusion of a timestamp in the511log message. If a function is supplied, it must synchronously return a partial JSON string512representation of the time, e.g. `,"time":1493426328206` (which is the default).513 514If set to `false`, no timestamp will be included in the output.515 516See [stdTimeFunctions](#pino-stdtimefunctions) for a set of available functions517for passing in as a value for this option.518 519Example:520```js521timestamp: () => `,"time":"${new Date(Date.now()).toISOString()}"`522// which is equivalent to:523// timestamp: stdTimeFunctions.isoTime524```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 531Default: `'msg'`532 533The string key for the 'message' in the JSON object.534 535<a id=opt-messagekey></a>536#### `errorKey` (String)537 538Default: `'err'`539 540The string key for the 'error' in the JSON object.541 542<a id=opt-nestedkey></a>543#### `nestedKey` (String)544 545Default: `null`546 547If there's a chance that objects being logged have properties that conflict with those from pino itself (`level`, `timestamp`, `pid`, etc)548and duplicate keys in your log records are undesirable, pino can be configured with a `nestedKey` option that causes any `object`s that are logged549to be placed under a key whose name is the value of `nestedKey`.550 551This 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 553For example,554```js555const logger = require('pino')({556  nestedKey: 'payload'557})558 559const thing = { level: 'hi', time: 'never', foo: 'bar'} // has pino-conflicting properties!560logger.info(thing)561 562// logs the following:563// {"level":30,"time":1578357790020,"pid":91736,"hostname":"x","payload":{"level":"hi","time":"never","foo":"bar"}}564```565In this way, logged objects' properties don't conflict with pino's standard logging properties,566and searching for logged objects can start from a consistent path.567 568#### `browser` (Object)569 570Browser only, may have `asObject` and `write` keys. This option is separately571documented in the [Browser API ⇗](/docs/browser.md) documentation.572 573* See [Browser API ⇗](/docs/browser.md)574 575#### `transport` (Object)576 577The `transport` option is a shorthand for the [pino.transport()](#pino-transport) function.578It supports the same input options:579```js580require('pino')({581  transport: {582    target: '/absolute/path/to/my-transport.mjs'583  }584})585 586// or multiple transports587require('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 597If the transport option is supplied to `pino`, a [`destination`](#destination) parameter may not also be passed as a separate argument to `pino`:598 599```js600pino({ transport: {}}, '/path/to/somewhere') // THIS WILL NOT WORK, DO NOT DO THIS601pino({ transport: {}}, process.stderr) // THIS WILL NOT WORK, DO NOT DO THIS602```603 604when using the `transport` option. In this case, an `Error` will be thrown.605 606* See [pino.transport()](#pino-transport)607 608#### `onChild` (Function)609 610The `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.611Any error thrown inside the callback will be uncaught and should be handled inside the callback.612```js613const 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.617parent.child(bindings)618```619 620 621<a id="destination"></a>622### `destination` (Number | String | Object | DestinationStream | SonicBoomOpts | WritableStream)623 624Default: `pino.destination(1)` (STDOUT)625 626The `destination` parameter can be a file descriptor, a file path, or an627object with `dest` property pointing to a fd or path.628An ordinary Node.js `stream` file descriptor can be passed as the629destination (such as the result630of `fs.createWriteStream`) but for peak log writing performance, it is strongly631recommended to use `pino.destination` to create the destination stream.632Note that the `destination` parameter can be the result of `pino.transport()`.633 634```js635// pino.destination(1) by default636const stdoutLogger = require('pino')()637 638// destination param may be in first position when no options:639const fileLogger = require('pino')( pino.destination('/log/path'))640 641// use the stderr file handle to log to stderr:642const opts = {name: 'my-logger'}643const stderrLogger = require('pino')(opts, pino.destination(2))644 645// automatic wrapping in pino.destination646const fileLogger = require('pino')('/log/path')647 648// Asynchronous logging649const fileLogger = pino(pino.destination({ dest: '/log/path', sync: false }))650```651 652However, 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 656In these cases `process.stdout` is used instead.657 658Note: If the parameter is a string integer, e.g. `'1'`, it will be coerced to659a number and used as a file descriptor. If this is not desired, provide a full660path, e.g. `/tmp/1`.661 662* See [`pino.destination`](#pino-destination)663 664<a id="metadata"></a>665#### `destination[Symbol.for('pino.metadata')]`666 667Default: `false`668 669Using the global symbol `Symbol.for('pino.metadata')` as a key on the `destination` parameter and670setting the key to `true`, indicates that the following properties should be671set 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 returned677  by the time function.678* the last logger instance as `destination.lastLogger` (to support child679  loggers)680 681The following is a succinct usage example:682 683```js684const dest = pino.destination('/dev/null')685dest[Symbol.for('pino.metadata')] = true686const logger = pino(dest)687logger.info({a: 1}, 'hi')688const { lastMsg, lastLevel, lastObj, lastTime} = dest689console.log(690  'Logged message "%s" at level %d with object %o at time %s',691  lastMsg, lastLevel, lastObj, lastTime692) // Logged message "hi" at level 30 with object { a: 1 } at time 1531590545089693```694 695<a id="logger"></a>696## Logger Instance697 698The logger instance is the object returned by the main exported699[`pino`](#export) function.700 701The primary purpose of the logger instance is to provide logging methods.702 703The default logging methods are `trace`, `debug`, `info`, `warn`, `error`, and `fatal`.704 705Each logging method has the following signature:706`([mergingObject], [message], [...interpolationValues])`.707 708The parameters are explained below using the `logger.info` method but the same applies to all logging methods.709 710### Logging Method Parameters711 712<a id=mergingobject></a>713#### `mergingObject` (Object)714 715An object can optionally be supplied as the first parameter. Each enumerable key and value716of the `mergingObject` is copied into the JSON log line.717 718```js719logger.info({MIX: {IN: true}})720// {"level":30,"time":1531254555820,"pid":55956,"hostname":"x","MIX":{"IN":true}}721```722 723If the object is of type Error, it is wrapped in an object containing a property err (`{ err: mergingObject }`).724This allows for a unified error handling flow.725 726Options `serializers` and `errorKey` could be used at instantiation time to change the namespace727from `err` to another string as preferred.728 729<a id="message"></a>730#### `message` (String)731 732A `message` string can optionally be supplied as the first parameter, or733as the second parameter after supplying a `mergingObject`.734 735By default, the contents of the `message` parameter will be merged into the736JSON log line under the `msg` key:737 738```js739logger.info('hello world')740// {"level":30,"time":1531257112193,"msg":"hello world","pid":55956,"hostname":"x"}741```742 743The `message` parameter takes precedence over the `mergingObject`.744That is, if a `mergingObject` contains a `msg` property, and a `message` parameter745is supplied in addition, the `msg` property in the output log will be the value of746the `message` parameter not the value of the `msg` property on the `mergingObject`.747See [Avoid Message Conflict](/docs/help.md#avoid-message-conflict) for information748on how to overcome this limitation.749 750If no `message` parameter is provided, and the `mergingObject` is of type `Error` or it has a property named `err`, the751`message` parameter is set to the `message` value of the error. See option `errorKey` if you want to change the namespace.752 753The `messageKey` option can be used at instantiation time to change the namespace754from `msg` to another string as preferred.755 756The `message` string may contain a printf style string with support for757the following placeholders:758 759* `%s` – string placeholder760* `%d` – digit placeholder761* `%O`, `%o`, and `%j` – object placeholder762 763Values supplied as additional arguments to the logger method will764then 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 772All arguments supplied after `message` are serialized and interpolated according773to any supplied printf-style placeholders (`%s`, `%d`, `%o`|`%O`|`%j`) to form774the final output `msg` value for the JSON log line.775 776```js777logger.info('%o hello %s', {worldly: 1}, 'world')778// {"level":30,"time":1531257826880,"msg":"{\"worldly\":1} hello world","pid":55956,"hostname":"x"}779```780 781Since pino v6, we do not automatically concatenate and cast to string782consecutive parameters:783 784```js785logger.info('hello', 'world')786// {"level":30,"time":1531257618044,"msg":"hello","pid":55956,"hostname":"x"}787// world is missing788```789 790However, it's possible to inject a hook to modify this behavior:791 792```js793const pinoOptions = {794  hooks: { logMethod }795}796 797function logMethod (args, method) {798  if (args.length === 2) {799    args[0] = `${args[0]} %j`800  }801  method.apply(this, args)802}803 804const 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#### Errors812 813Errors can be supplied as either the first parameter or if already using `mergingObject` then as the `err` property on the `mergingObject`.814 815Options `serializers` and `errorKey` could be used at instantiation time to change the namespace816from `err` to another string as preferred.817 818> ## Note819> This section describes the default configuration. The error serializer can be820> mapped to a different key using the [`serializers`](#opt-serializers) option.821```js822logger.info(new Error("test"))823// {"level":30,"time":1531257618044,"msg":"test","stack":"...","type":"Error","pid":55956,"hostname":"x"}824 825logger.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 832Write 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 841Write 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 850Write 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 859Write 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 868Write 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 877Write a `'fatal'` level log, if the configured `level` allows for it.878 879Since `'fatal'` level messages are intended to be logged just before the process exiting the `fatal`880method will always sync flush the destination.881Therefore it's important not to misuse `fatal` since882it will cause performance overhead if used for any883other purpose than writing final log messages before884the 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 893Noop function.894 895<a id="child"></a>896### `logger.child(bindings, [options]) => logger`897 898The `logger.child` method allows for the creation of stateful loggers,899where key-value pairs can be pinned to a logger causing them to be output900on every log line.901 902Child loggers use the same output stream as the parent and inherit903the current log level of the parent at the time they are spawned.904 905The log level of a child is mutable. It can be set independently906of the parent either by setting the [`level`](#level) accessor after creating907the child logger or using the [`options.level`](#optionslevel-string) key.908 909<a id="logger-child-bindings"></a>910#### `bindings` (Object)911 912An object of key-value pairs to include in every log line output913via the returned child logger.914 915```js916const child = logger.child({ MIX: {IN: 'always'} })917child.info('hello')918// {"level":30,"time":1531258616689,"msg":"hello","pid":64849,"hostname":"x","MIX":{"IN":"always"}}919child.info('child!')920// {"level":30,"time":1531258617401,"msg":"child!","pid":64849,"hostname":"x","MIX":{"IN":"always"}}921```922 923The `bindings` object may contain any key except for reserved configuration keys `level` and `serializers`.924 925##### `bindings.serializers` (Object) - DEPRECATED926 927Use `options.serializers` instead.928 929#### `options` (Object)930 931Options for child logger. These options will override the parent logger options.932 933##### `options.level` (String)934 935The `level` property overrides the log level of the child logger.936By default, the parent log level is inherited.937After the creation of the child logger, it is also accessible using the [`logger.level`](#logger-level) key.938 939```js940const logger = pino()941logger.debug('nope') // will not log, since default level is info942const child = logger.child({foo: 'bar'}, {level: 'debug'})943child.debug('debug!') // will log as the `level` property set the level to debug944```945 946##### `options.msgPrefix` (String)947 948Default: `undefined`949 950The `msgPrefix` property allows you to specify a prefix for every message of the child logger.951By default, the parent prefix is inherited.952If the parent already has a prefix, the prefix of the parent and then the child will be displayed.953 954```js955const logger = pino({956  msgPrefix: '[HTTP] '957})958logger.info('got new request!')959// >  [HTTP] got new request!960 961const child = logger.child({avengers: 'assemble'}, {msgPrefix: '[Proxy] '})962child.info('message proxied!')963// >  [HTTP] [Proxy] message proxied!964```965 966##### `options.redact` (Array | Object)967 968Setting `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```js971const logger = require('pino')({ redact: ['hello'] })972logger.info({ hello: 'world' })973// {"level":30,"time":1625794363403,"pid":67930,"hostname":"x","hello":"[Redacted]"}974const child = logger.child({ foo: 'bar' }, { redact: ['foo'] })975logger.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 983Child loggers inherit the [serializers](#opt-serializers) from the parent logger.984 985Setting the `serializers` key of the `options` object will override986any configured parent serializers.987 988```js989const logger = require('pino')()990logger.info({test: 'will appear'})991// {"level":30,"time":1531259759482,"pid":67930,"hostname":"x","test":"will appear"}992const child = logger.child({}, {serializers: {test: () => `child-only serializer`}})993child.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 1003Returns an object containing all the current bindings, cloned from the ones passed in via `logger.child()`.1004```js1005const child = logger.child({ foo: 'bar' })1006console.log(child.bindings())1007// { foo: 'bar' }1008const anotherChild = child.child({ MIX: { IN: 'always' } })1009console.log(anotherChild.bindings())1010// { foo: 'bar', MIX: { IN: 'always' } }1011```1012 1013<a id="logger-set-bindings"></a>1014### `logger.setBindings(bindings)`1015 1016Adds to the bindings of this logger instance.1017 1018**Note:** Does not overwrite bindings. Can potentially result in duplicate keys in1019log lines.1020 1021* See [`bindings` parameter in `logger.child`](#logger-child-bindings)1022 1023<a id="flush"></a>1024### `logger.flush([cb])`1025 1026Flushes the content of the buffer when using `pino.destination({1027sync: false })`.1028 1029This is an asynchronous, best used as fire and forget, operation.1030 1031The use case is primarily for asynchronous logging, which may buffer1032log lines while others are being written. The `logger.flush` method can be1033used to flush the logs1034on a long interval, say ten seconds. Such a strategy can provide an1035optimum balance between extremely efficient logging at high demand periods1036and safer logging at low demand periods.1037 1038If 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 1046Set this property to the desired logging level.1047 1048The 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 1055The logging level is a *minimum* level based on the associated value of that level.1056 1057For 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 1059The `silent` logging level is a specialized level that will disable all logging,1060the `silent` log method is a noop function.1061 1062<a id="islevelenabled"></a>1063### `logger.isLevelEnabled(level)`1064 1065A utility method for determining if a given log level will write to the destination.1066 1067#### `level` (String)1068 1069The given level to check against:1070 1071```js1072if (logger.isLevelEnabled('debug')) logger.debug('conditional log')1073```1074 1075#### `levelLabel` (String)1076 1077Defines the method name of the new level.1078 1079* See [`logger.level`](#level)1080 1081#### `levelValue` (Number)1082 1083Defines the associated minimum threshold value for the level, and1084therefore 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 1091Supplies the integer value for the current logging level.1092 1093```js1094if (logger.levelVal === 30) {1095  console.log('logger level is `info`')1096}1097```1098 1099<a id="levels"></a>1100### `logger.levels` (Object)1101 1102Levels are mapped to values to determine the minimum threshold that a1103logging method should be enabled at (see [`logger.level`](#level)).1104 1105The `logger.levels` property holds the mappings between levels and values,1106and vice versa.1107 1108```sh1109$ node -p "require('pino')().levels"1110```1111 1112```js1113{ 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 1129Returns the serializers as applied to the current logger instance. If a child logger did not1130register 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 1135The logger instance is also an [`EventEmitter ⇗`](https://nodejs.org/dist/latest/docs/api/events.html#events_class_eventemitter)1136 1137A listener function can be attached to a logger via the `level-change` event1138 1139The 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 originated1146 1147```js1148const logger = require('pino')()1149logger.on('level-change', (lvl, val, prevLvl, prevVal) => {1150  console.log('%s (%d) was changed to %s (%d)', prevLvl, prevVal, lvl, val)1151})1152logger.level = 'trace' // trigger event1153```1154 1155Please note that due to a [known bug](https://github.com/pinojs/pino/issues/1006), every `logger.child()` call will1156fire a `level-change` event. These events can be ignored by writing an event handler like:1157 1158```js1159const logger = require('pino')()1160logger.on('level-change', function (lvl, val, prevLvl, prevVal, instance) {1161  if (logger !== instance) {1162    return1163  }1164  console.log('%s (%d) was changed to %s (%d)', prevLvl, prevVal, lvl, val)1165})1166logger.child({}); // trigger an event by creating a child instance, notice no console.log1167logger.level = 'trace' // trigger event using actual value change, notice console.log1168```1169 1170<a id="version"></a>1171### `logger.version` (String)1172 1173Exposes the Pino package version. Also available on the exported `pino` function.1174 1175* See [`pino.version`](#pino-version)1176 1177## Statics1178 1179<a id="pino-destination"></a>1180### `pino.destination([opts]) => SonicBoom`1181 1182Create a Pino Destination instance: a stream-like object with1183significantly more throughput than a standard Node.js stream.1184 1185```js1186const pino = require('pino')1187const logger = pino(pino.destination('./my-file'))1188const logger2 = pino(pino.destination())1189const logger3 = pino(pino.destination({1190  dest: './my-file',1191  minLength: 4096, // Buffer before writing1192  sync: false // Asynchronous logging, the default1193}))1194const logger4 = pino(pino.destination({1195  dest: './my-file2',1196  sync: true // Synchronous logging1197}))1198```1199 1200The `pino.destination` method may be passed a file path or a numerical file descriptor.

Showing the first 1,200 of 1488 lines. Download the file for the rest.