Merge branch 'master' into next

This commit is contained in:
Matteo Collina 2021-04-06 18:45:21 +02:00
commit cba70129a8
82 changed files with 1029 additions and 864 deletions

View File

@ -1 +1,8 @@
{ "extends": "standard" }
{
"extends": [
"standard"
],
"rules": {
"no-var": "off"
}
}

12
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,12 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10

View File

@ -13,7 +13,7 @@ jobs:
with:
ref: ${{ github.base_ref }}
- name: Setup Node
uses: actions/setup-node@v1
uses: actions/setup-node@v2.1.5
with:
node-version: 12
- name: Install Modules
@ -21,7 +21,7 @@ jobs:
- name: Run Benchmark
run: npm run bench | tee current.txt
- name: Upload Current Results
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v2.2.2
with:
name: current
path: current.txt
@ -33,7 +33,7 @@ jobs:
- name: Checkout Code
uses: actions/checkout@v2
- name: Setup Node
uses: actions/setup-node@v1
uses: actions/setup-node@v2.1.5
with:
node-version: 12
- name: Install Modules
@ -41,7 +41,7 @@ jobs:
- name: Run Benchmark
run: npm run bench | tee branch.txt
- name: Upload Branch Results
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v2.2.2
with:
name: branch
path: branch.txt

View File

@ -1,5 +1,13 @@
name: CI
on: [push, pull_request]
on:
push:
paths-ignore:
- "docs/**"
- "*.md"
pull_request:
paths-ignore:
- "docs/**"
- "*.md"
jobs:
test:
name: ${{ matrix.node-version }} ${{ matrix.os }}
@ -12,10 +20,35 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
uses: actions/setup-node@v2.1.5
with:
node-version: ${{ matrix.node-version }}
- name: Install
run: npm i
- name: Tests
run: npm test
run: npm run test-ci
- name: Coveralls Parallel
uses: coverallsapp/github-action@v1.1.2
with:
github-token: ${{ secrets.github_token }}
parallel: true
flag-name: run-${{ matrix.node-version }}-${{ matrix.os }}
coverage:
needs: test
runs-on: ubuntu-latest
steps:
- name: Coveralls Finished
uses: coverallsapp/github-action@v1.1.2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
parallel-finished: true
automerge:
needs: test
runs-on: ubuntu-latest
steps:
- uses: fastify/github-action-merge-dependabot@v1.2.1
if: ${{ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request' }}
with:
github-token: ${{secrets.github_token}}

3
.taprc
View File

@ -1,5 +1,2 @@
esm: false
ts: false
jsx: false
coverage: true
timeout: 480

View File

@ -1,9 +1,12 @@
![banner](pino-banner.png)
# pino
[![npm version](https://img.shields.io/npm/v/pino)](https://www.npmjs.com/package/pino)
[![Build Status](https://img.shields.io/github/workflow/status/pinojs/pino/CI)](https://github.com/pinojs/pino/actions)
 [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/)
 [![TypeScript definitions on DefinitelyTyped](https://img.shields.io/badge/DefinitelyTyped-.d.ts-brightgreen.svg?style=flat)](https://definitelytyped.org)
[![Known Vulnerabilities](https://snyk.io/test/github/pinojs/pino/badge.svg)](https://snyk.io/test/github/pinojs/pino)
[![Coverage Status](https://coveralls.io/repos/github/pinojs/pino/badge.svg?branch=master)](https://coveralls.io/github/pinojs/pino?branch=master)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
[![TypeScript definitions on DefinitelyTyped](https://img.shields.io/badge/DefinitelyTyped-.d.ts-brightgreen.svg?style=flat)](https://definitelytyped.org)
[Very low overhead](#low-overhead) Node.js logger.
@ -134,7 +137,7 @@ See the [CONTRIBUTING.md](https://github.com/pinojs/pino/blob/master/CONTRIBUTIN
<a name="acknowledgements"></a>
## Acknowledgements
This project was kindly sponsored by [nearForm](http://nearform.com).
This project was kindly sponsored by [nearForm](https://nearform.com).
Logo and identity designed by Cosmic Fox Design: https://www.behance.net/cosmicfox.

View File

@ -27,35 +27,35 @@ require('bole').output({
const run = bench([
function benchBunyanCreation (cb) {
var child = blog.child({ a: 'property' })
const child = blog.child({ a: 'property' })
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchBoleCreation (cb) {
var child = bole('child')
const child = bole('child')
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoCreation (cb) {
var child = plogDest.child({ a: 'property' })
const child = plogDest.child({ a: 'property' })
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoAsyncCreation (cb) {
var child = plogAsync.child({ a: 'property' })
const child = plogAsync.child({ a: 'property' })
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoNodeStreamCreation (cb) {
var child = plogNodeStream.child({ a: 'property' })
const child = plogNodeStream.child({ a: 'property' })
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}

View File

@ -92,14 +92,14 @@ const run = bench([
setImmediate(cb)
},
function benchPinoChildCreation (cb) {
var child = plog.child({ a: 'property' })
const child = plog.child({ a: 'property' })
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoDestChildCreation (cb) {
var child = plogDest.child({ a: 'property' })
const child = plogDest.child({ a: 'property' })
for (var i = 0; i < max; i++) {
child.info({ hello: 'world' })
}

View File

@ -31,7 +31,7 @@ require('bole').output({
stream: dest
}).setFastTime(true)
var chill = winston.createLogger({
const chill = winston.createLogger({
transports: [
new winston.transports.Stream({
stream: fs.createWriteStream('/dev/null')
@ -39,7 +39,7 @@ var chill = winston.createLogger({
]
})
var run = bench([
const run = bench([
function benchBunyan (cb) {
for (var i = 0; i < max; i++) {
blog.info(longStr)

View File

@ -90,7 +90,7 @@ function runBenchmark (name, done) {
}
function sum (arr) {
var result = 0
let result = 0
for (var i = 0; i < arr.length; i += 1) {
result += Number.parseFloat(arr[i].time)
}
@ -105,8 +105,8 @@ function displayResults (results) {
const benchmark = results[benchNames[i]]
const loggers = Object.keys(benchmark)
for (var j = 0; j < loggers.length; j += 1) {
var logger = benchmark[loggers[j]]
var average = sum(logger) / logger.length
const logger = benchmark[loggers[j]]
const average = sum(logger) / logger.length
console.log(`${loggers[j]} average: ${average.toFixed(3)}ms`)
}
}

View File

@ -9,24 +9,24 @@ const code = readFileSync(
const { Console } = require('console')
function build (dest) {
var sandbox = {
const sandbox = {
module: {},
console: new Console(dest, dest)
}
var context = vm.createContext(sandbox)
const context = vm.createContext(sandbox)
var script = new vm.Script(code)
const script = new vm.Script(code)
script.runInContext(context)
var loglevel = sandbox.log
const loglevel = sandbox.log
var originalFactory = loglevel.methodFactory
const originalFactory = loglevel.methodFactory
loglevel.methodFactory = function (methodName, logLevel, loggerName) {
var rawMethod = originalFactory(methodName, logLevel, loggerName)
const rawMethod = originalFactory(methodName, logLevel, loggerName)
return function () {
var time = new Date()
var array
const time = new Date()
let array
if (typeof arguments[0] === 'string') {
arguments[0] = '[' + time.toISOString() + '] ' + arguments[0]
rawMethod.apply(null, arguments)
@ -48,7 +48,7 @@ function build (dest) {
module.exports = build
if (require.main === module) {
var loglevel = build(process.stdout)
const loglevel = build(process.stdout)
loglevel.info('hello')
loglevel.info({ hello: 'world' })
loglevel.info('hello %j', { hello: 'world' })

View File

@ -1,11 +1,11 @@
'use strict'
var format = require('quick-format-unescaped')
const format = require('quick-format-unescaped')
module.exports = pino
var _console = pfGlobalThisOrFallback().console || {}
var stdSerializers = {
const _console = pfGlobalThisOrFallback().console || {}
const stdSerializers = {
mapHttpRequest: mock,
mapHttpResponse: mock,
wrapRequestSerializer: passthrough,
@ -16,37 +16,46 @@ var stdSerializers = {
err: asErrValue
}
function shouldSerialize (serialize, serializers) {
if (Array.isArray(serialize)) {
const hasToFilter = serialize.filter(function (k) {
return k !== '!stdSerializers.err'
})
return hasToFilter
} else if (serialize === true) {
return Object.keys(serializers)
}
return false
}
function pino (opts) {
opts = opts || {}
opts.browser = opts.browser || {}
var transmit = opts.browser.transmit
const transmit = opts.browser.transmit
if (transmit && typeof transmit.send !== 'function') { throw Error('pino: transmit option must have a send function') }
var proto = opts.browser.write || _console
const proto = opts.browser.write || _console
if (opts.browser.write) opts.browser.asObject = true
var serializers = opts.serializers || {}
var serialize = Array.isArray(opts.browser.serialize)
? opts.browser.serialize.filter(function (k) {
return k !== '!stdSerializers.err'
})
: opts.browser.serialize === true ? Object.keys(serializers) : false
var stdErrSerialize = opts.browser.serialize
const serializers = opts.serializers || {}
const serialize = shouldSerialize(opts.browser.serialize, serializers)
let stdErrSerialize = opts.browser.serialize
if (
Array.isArray(opts.browser.serialize) &&
opts.browser.serialize.indexOf('!stdSerializers.err') > -1
) stdErrSerialize = false
var levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace']
const levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace']
if (typeof proto === 'function') {
proto.error = proto.fatal = proto.warn =
proto.info = proto.debug = proto.trace = proto
}
if (opts.enabled === false) opts.level = 'silent'
var level = opts.level || 'info'
var logger = Object.create(proto)
const level = opts.level || 'info'
const logger = Object.create(proto)
if (!logger.log) logger.log = noop
Object.defineProperty(logger, 'levelVal', {
@ -57,7 +66,7 @@ function pino (opts) {
set: setLevel
})
var setOpts = {
const setOpts = {
transmit,
serialize,
asObject: opts.browser.asObject,
@ -108,7 +117,7 @@ function pino (opts) {
if (!bindings) {
throw new Error('missing bindings for child Pino')
}
var bindingsSerializers = bindings.serializers
const bindingsSerializers = bindings.serializers
if (serialize && bindingsSerializers) {
var childSerializers = Object.assign({}, serializers, bindingsSerializers)
var childSerialize = opts.browser.serialize === true
@ -164,8 +173,9 @@ pino.stdSerializers = stdSerializers
pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime })
function set (opts, logger, level, fallback) {
var proto = Object.getPrototypeOf(logger)
logger[level] = logger.levelVal > logger.levels.values[level] ? noop
const proto = Object.getPrototypeOf(logger)
logger[level] = logger.levelVal > logger.levels.values[level]
? noop
: (proto[level] ? proto[level] : (_console[level] || _console[fallback] || noop))
wrap(opts, logger, level)
@ -176,9 +186,9 @@ function wrap (opts, logger, level) {
logger[level] = (function (write) {
return function LOG () {
var ts = opts.timestamp()
var args = new Array(arguments.length)
var proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this
const ts = opts.timestamp()
const args = new Array(arguments.length)
const proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this
for (var i = 0; i < args.length; i++) args[i] = arguments[i]
if (opts.serialize && !opts.asObject) {
@ -188,9 +198,9 @@ function wrap (opts, logger, level) {
else write.apply(proto, args)
if (opts.transmit) {
var transmitLevel = opts.transmit.level || logger.level
var transmitValue = pino.levels.values[transmitLevel]
var methodValue = pino.levels.values[level]
const transmitLevel = opts.transmit.level || logger.level
const transmitValue = pino.levels.values[transmitLevel]
const methodValue = pino.levels.values[level]
if (methodValue < transmitValue) return
transmit(this, {
ts,
@ -208,14 +218,14 @@ function wrap (opts, logger, level) {
function asObject (logger, level, args, ts) {
if (logger._serialize) applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize)
var argsCloned = args.slice()
var msg = argsCloned[0]
var o = {}
const argsCloned = args.slice()
let msg = argsCloned[0]
const o = {}
if (ts) {
o.time = ts
}
o.level = pino.levels.values[level]
var lvl = (logger._childLevel | 0) + 1
let lvl = (logger._childLevel | 0) + 1
if (lvl < 1) lvl = 1
// deliberate, catching objects, arrays
if (msg !== null && typeof msg === 'object') {
@ -229,11 +239,11 @@ function asObject (logger, level, args, ts) {
}
function applySerializers (args, serialize, serializers, stdErrSerialize) {
for (var i in args) {
for (const i in args) {
if (stdErrSerialize && args[i] instanceof Error) {
args[i] = pino.stdSerializers.err(args[i])
} else if (typeof args[i] === 'object' && !Array.isArray(args[i])) {
for (var k in args[i]) {
for (const k in args[i]) {
if (serialize && serialize.indexOf(k) > -1 && k in serializers) {
args[i][k] = serializers[k](args[i][k])
}
@ -244,7 +254,7 @@ function applySerializers (args, serialize, serializers, stdErrSerialize) {
function bind (parent, bindings, level) {
return function () {
var args = new Array(1 + arguments.length)
const args = new Array(1 + arguments.length)
args[0] = bindings
for (var i = 1; i < args.length; i++) {
args[i] = arguments[i - 1]
@ -254,12 +264,12 @@ function bind (parent, bindings, level) {
}
function transmit (logger, opts, args) {
var send = opts.send
var ts = opts.ts
var methodLevel = opts.methodLevel
var methodValue = opts.methodValue
var val = opts.val
var bindings = logger._logEvent.bindings
const send = opts.send
const ts = opts.ts
const methodLevel = opts.methodLevel
const methodValue = opts.methodValue
const val = opts.val
const bindings = logger._logEvent.bindings
applySerializers(
args,
@ -291,12 +301,12 @@ function createLogEventShape (bindings) {
}
function asErrValue (err) {
var obj = {
const obj = {
type: err.constructor.name,
msg: err.message,
stack: err.stack
}
for (var key in err) {
for (const key in err) {
if (obj[key] === undefined) {
obj[key] = err[key]
}

View File

@ -124,18 +124,16 @@ const mixin = {
}
const logger = pino({
mixin(obj) {
return {
description: obj.description
}
mixin() {
return mixin;
}
})
pino.info({
logger.info({
description: 'Ok'
}, 'Message 1')
// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","appName":"My app","description":"Ok" "msg":"Message 1"}
pino.info('Message 2')
logger.info('Message 2')
// {"level":30,"time":1591195061437,"pid":16012,"hostname":"x","appName":"My app","description":"Ok","msg":"Message 2"}
// Note: the second log contains "description":"Ok" text, even if it was not provided.
```
@ -154,7 +152,7 @@ Each path must be a string using a syntax which corresponds to JavaScript dot an
If an object is supplied, three options can be specified:
* `paths` (array): Required. An array of paths. See [redaction - Path Syntax ⇗](/docs/redaction.md#paths) for specifics.
* `censor` (String|Function|Undefined): Optional. When supplied as a String the `censor` option will overwrite keys which are to be redacted. When set to `undefined` the the key will be removed entirely from the object.
* `censor` (String|Function|Undefined): Optional. When supplied as a String the `censor` option will overwrite keys which are to be redacted. When set to `undefined` the key will be removed entirely from the object.
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]'`
value synchronously.
Default: `'[Redacted]'`
@ -163,7 +161,7 @@ If an object is supplied, three options can be specified:
**WARNING**: Never allow user input to define redacted paths.
* See the [redaction ⇗](/docs/redaction.md) documentation.
* See [fast-redact#caveat ⇗](http://github.com/davidmarkclements/fast-redact#caveat)
* See [fast-redact#caveat ⇗](https://github.com/davidmarkclements/fast-redact#caveat)
<a id=opt-hooks></a>
#### `hooks` (Object)
@ -175,10 +173,10 @@ internal logger operations. Hook functions ***must*** be synchronous functions.
##### `logMethod`
Allows for manipulating the parameters passed to logger methods. The signature
for this hook is `logMethod (args, method) {}`, where `args` is an array
for this hook is `logMethod (args, method, level) {}`, where `args` is an array
of the arguments that were passed to the log method and `method` is the log
method itself. This hook ***must*** invoke the `method` function by using
apply, like so: `method.apply(this, newArgumentsArray)`.
method itself, `level` is the log level itself. This hook ***must*** invoke the
`method` function by using apply, like so: `method.apply(this, newArgumentsArray)`.
For example, Pino expects a binding object to be the first parameter with an
optional string message as the second parameter. Using this hook the parameters
@ -186,7 +184,7 @@ can be flipped:
```js
const hooks = {
logMethod (inputArgs, method) {
logMethod (inputArgs, method, level) {
if (inputArgs.length >= 2) {
const arg1 = inputArgs.shift()
const arg2 = inputArgs.shift()
@ -295,13 +293,21 @@ Set to `true` to logs newline delimited JSON with `\r\n` instead of `\n`.
Default: `true`
Enables or disables the inclusion of a timestamp in the
log message. If a function is supplied, it must synchronously return a JSON string
log message. If a function is supplied, it must synchronously return a partial JSON string
representation of the time, e.g. `,"time":1493426328206` (which is the default).
If set to `false`, no timestamp will be included in the output.
See [stdTimeFunctions](#pino-stdtimefunctions) for a set of available functions
for passing in as a value for this option.
Example:
```js
timestamp: () => `,"time":"${new Date(Date.now()).toISOString()}"`
// which is equivalent to:
// timestamp: stdTimeFunctions.isoTime
```
**Caution**: attempting to format time in-process will significantly impact logging performance.
<a id=opt-messagekey></a>
@ -497,7 +503,7 @@ The `message` parameter takes precedence over the `mergedObject`.
That is, if a `mergedObject` contains a `msg` property, and a `message` parameter
is supplied in addition, the `msg` property in the output log will be the value of
the `message` parameter not the value of the `msg` property on the `mergedObject`.
See [Avoid Message Conflict](./help.md#avoid-message-conflict) for information
See [Avoid Message Conflict](/docs/help.md#avoid-message-conflict) for information
on how to overcome this limitation.
If no `message` parameter is provided, and the `mergedObject` is of type `Error` or it has a property named `err`, the
@ -560,6 +566,22 @@ const logger = pino(pinoOptions)
* See [`message` log method parameter](#message)
* See [`logMethod` hook](#logmethod)
<a id="error-serialization"></a>
#### Errors
Errors can be supplied as either the first parameter or if already using `mergingObject` then as the `err` property on the `mergingObject`.
> ## Note
> This section describes the default configuration. The error serializer can be
> mapped to a different key using the [`serializers`](#opt-serializers) option.
```js
logger.info(new Error("test"))
// {"level":30,"time":1531257618044,"msg":"test","stack":"...","type":"Error","pid":55956,"hostname":"x"}
logger.info({ err: new Error("test"), otherkey: 123 }, "some text")
// {"level":30,"time":1531257618044,"err":{"msg": "test", "stack":"...","type":"Error"},"msg":"some text","pid":55956,"hostname":"x","otherkey":123}
```
<a id="trace"></a>
### `logger.trace([mergingObject], [message], [...interpolationValues])`
@ -823,7 +845,7 @@ The listener is passed four arguments:
```js
const logger = require('pino')()
logger.on('level-change', (lvl, val, prevLvl, prevVal) => {
console.log('%s (%d) was changed to %s (%d)', lvl, val, prevLvl, prevVal)
console.log('%s (%d) was changed to %s (%d)', prevLvl, prevVal, lvl, val)
})
logger.level = 'trace' // trigger event
```

View File

@ -51,6 +51,6 @@ PinoAsyncInterpolateExtra average: 209.552ms
PinoNodeStreamInterpolateExtra average: 413.195ms
```
For a fair comparison, [LogLevel](http://npm.im/loglevel) was extended
to include a timestamp and [bole](http://npm.im/bole) had
For a fair comparison, [LogLevel](https://npm.im/loglevel) was extended
to include a timestamp and [bole](https://npm.im/bole) had
`fastTime` mode switched on.

View File

@ -1,6 +1,6 @@
# Browser API
Pino is compatible with [`browserify`](http://npm.im/browserify) for browser side usage:
Pino is compatible with [`browserify`](https://npm.im/browserify) for browser side usage:
This can be useful with isomorphic/universal JavaScript code.

View File

@ -14,7 +14,7 @@ Please send a PR to add new modules!
+ [`express-pino-logger`](https://github.com/pinojs/express-pino-logger): use
Pino to log requests within [express](https://expressjs.com/).
+ [`koa-pino-logger`](https://github.com/pinojs/koa-pino-logger): use Pino to
log requests within [Koa](http://koajs.com/).
log requests within [Koa](https://koajs.com/).
+ [`pino-arborsculpture`](https://github.com/pinojs/pino-arborsculpture): change
log levels at runtime.
+ [`pino-caller`](https://github.com/pinojs/pino-caller): add callsite to the log line.
@ -70,3 +70,4 @@ prettifier inspired by the [logrus](https://github.com/sirupsen/logrus) logger.
+ [`pino-rotating-file`](https://github.com/homeaway/pino-rotating-file): a hapi-pino log transport for splitting logs into separate, automatically rotating files.
+ [`cls-proxify`](https://github.com/keenondrums/cls-proxify): integration of pino and [CLS](https://github.com/jeff-lewis/cls-hooked). Useful for creating dynamically configured child loggers (e.g. with added trace ID) for each request.
+ [`pino-tiny`](https://github.com/holmok/pino-tiny): a tiny (and exentsible?) little log formatter for pino.
+ [`pino-dev`](https://github.com/dnjstrom/pino-dev): simple prettifier for pino with built-in support for common ecosystem packages.

View File

@ -120,7 +120,7 @@ Given a similar scenario as in the [Log rotation](#rotate) section a basic
Let's assume we want to store all error messages to a separate log file.
Install [pino-tee](http://npm.im/pino-tee) with:
Install [pino-tee](https://npm.im/pino-tee) with:
```bash
npm i pino-tee -g
@ -209,15 +209,15 @@ the logs human friendly.
<a id="debug"></a>
## Pino with `debug`
The popular [`debug`](http://npm.im/debug) is used in many modules across the ecosystem.
The popular [`debug`](https://npm.im/debug) is used in many modules across the ecosystem.
The [`pino-debug`](http://github.com/pinojs/pino-debug) module
The [`pino-debug`](https://github.com/pinojs/pino-debug) module
can capture calls to `debug` loggers and run them
through `pino` instead. This results in a 10x (20x in asynchronous mode)
performance improvement - even though `pino-debug` is logging additional
data and wrapping it in JSON.
To quickly enable this install [`pino-debug`](http://github.com/pinojs/pino-debug)
To quickly enable this install [`pino-debug`](https://github.com/pinojs/pino-debug)
and preload it with the `-r` flag, enabling any `debug` logs with the
`DEBUG` environment variable:
@ -226,8 +226,8 @@ $ npm i pino-debug
$ DEBUG=* node -r pino-debug app.js
```
[`pino-debug`](http://github.com/pinojs/pino-debug) also offers fine grain control to map specific `debug`
namespaces to `pino` log levels. See [`pino-debug`](http://github.com/pinojs/pino-debug)
[`pino-debug`](https://github.com/pinojs/pino-debug) also offers fine grain control to map specific `debug`
namespaces to `pino` log levels. See [`pino-debug`](https://github.com/pinojs/pino-debug)
for more.
<a id="windows"></a>
@ -287,10 +287,10 @@ module.exports = function createLogger(options) {
<a id="avoid-message-conflict"></a>
## Avoid Message Conflict
As described in the [`message` documentation](./api.md#message), when a log
As described in the [`message` documentation](/docs/api.md#message), when a log
is written like `log.info({ msg: 'a message' }, 'another message')` then the
final output JSON will have `"msg":"another message"` and the `'a message'`
string will be lost. To overcome this, the [`logMethod` hook](./api.md#logmethod)
string will be lost. To overcome this, the [`logMethod` hook](/docs/api.md#logmethod)
can be used:
```js

View File

@ -26,7 +26,7 @@ Node v0.10 or Node v0.12 is supported on the [Pino v2](#pino-v2-documentation) l
## Migration
### Pino v4 to to Pino v5
### Pino v4 to Pino v5
#### Logging Destination

View File

@ -1,12 +1,14 @@
## Long Term Support
<a id="lts"></a>
Pino's Long Term Support (LTS) is tied to the
[Node.js LTS policy](https://github.com/nodejs/Release). Major versions of
Pino, "X" releases in X.Y.Z of [semantic versioning][semver] nomenclature, will
Pino's Long Term Support (LTS) is tied to the [Node.js LTS policy].
Major versions of Pino, "X" releases in X.Y.Z of [semantic versioning] nomenclature, will
be issued as close as possible to the release of a new major LTS release of
Node.js (subject to the Pino maintainers's capcity). Pino makes no guarantees
Node.js (subject to the Pino maintainers's capacity). Pino makes no guarantees
as to the operability of the library on unsupported releases of Node.js.
Pino will not remove support for a deprecated Node.js release via a minor,
or patch, release of Pino.
[semantic versioning]: https://semver.org/
[Node.js LTS policy]: https://github.com/nodejs/Release

View File

@ -21,7 +21,7 @@ log lines piped via `stdin` and expose an API which conforms to the Pino
The API requires modules provide a factory function which returns a prettifier
function. This prettifier function must accept either a string of NDJSON or
a Pino log object. A psuedo-example of such a prettifier is:
a Pino log object. A pseudo-example of such a prettifier is:
The uninitialized Pino instance is passed as `this` into prettifier factory function,
so it can be accessed via closure by the returned prettifier function.

View File

@ -115,7 +115,7 @@ By way of example, the following are all valid paths:
## Overhead
Pino's redaction functionality is built on top of [`fast-redact`](http://github.com/davidmarkclements/fast-redact)
Pino's redaction functionality is built on top of [`fast-redact`](https://github.com/davidmarkclements/fast-redact)
which adds about 2% overhead to `JSON.stringify` when using paths without wildcards.
When used with pino logger with a single redacted path, any overhead is within noise -

View File

@ -1,6 +1,6 @@
# Transports
A "transport" for Pino is supplementary tool which consumes Pino logs.
A "transport" for Pino is a supplementary tool which consumes Pino logs.
Consider the following example:
@ -42,7 +42,7 @@ external processes so that the threading capabilities of the OS can be
used (or other CPUs).
One consequence of this methodology is that "error" logs do not get written to
`stderr`. However, since Pino logs are in a parseable format, it is possible to
`stderr`. However, since Pino logs are in a parsable format, it is possible to
use tools like [pino-tee][pino-tee] or [jq][jq] to work with the logs. For
example, to view only logs marked as "error" logs:
@ -76,6 +76,8 @@ PR's to this document are welcome for any new transports!
+ [pino-elasticsearch](#pino-elasticsearch)
+ [pino-gelf](#pino-gelf)
+ [pino-http-send](#pino-http-send)
+ [pino-kafka](#pino-kafka)
+ [pino-logdna](#pino-logdna)
+ [pino-logflare](#pino-logflare)
+ [pino-mq](#pino-mq)
+ [pino-mysql](#pino-mysql)
@ -83,6 +85,7 @@ PR's to this document are welcome for any new transports!
+ [pino-pg](#pino-pg)
+ [pino-redis](#pino-redis)
+ [pino-sentry](#pino-sentry)
+ [pino-seq](#pino-seq)
+ [pino-socket](#pino-socket)
+ [pino-stackdriver](#pino-stackdriver)
+ [pino-syslog](#pino-syslog)
@ -210,6 +213,26 @@ transport that will batch logs and send to a specified URL.
$ node app.js | pino-http-send -u http://localhost:8080/logs
```
<a id="pino-kafka"></a>
### pino-kafka
[pino-kafka](https://github.com/ayZagen/pino-kafka) transport to send logs to [Apache Kafka](https://kafka.apache.org/).
```sh
$ node index.js | pino-kafka -b 10.10.10.5:9200 -d mytopic
```
<a id="pino-logdna"></a>
### pino-logdna
[pino-logdna](https://github.com/logdna/pino-logdna) transport to send logs to [LogDNA](https://logdna.com).
```sh
$ node index.js | pino-logdna --key YOUR_INGESTION_KEY
```
Tags and other metadata can be included using the available command line options. See the [pino-logdna readme](https://github.com/logdna/pino-logdna#options) for a full list.
<a id="pino-logflare"></a>
### pino-logflare
@ -311,6 +334,19 @@ For full documentation of command line switches see the [pino-sentry readme](htt
[pino-sentry]: https://www.npmjs.com/package/pino-sentry
[Sentry]: https://sentry.io/
<a id="pino-seq"></a>
### pino-seq
[pino-seq][pino-seq] supports both out-of-process and in-process log forwarding to [Seq][Seq].
```sh
$ node app.js | pino-seq --serverUrl http://localhost:5341 --apiKey 1234567890 --property applicationName=MyNodeApp
```
[pino-seq]: https://www.npmjs.com/package/pino-seq
[Seq]: https://datalust.co/seq
<a id="pino-socket"></a>
### pino-socket
@ -416,4 +452,4 @@ Example output for the "hello world" log:
$ node app.js | pino-websocket -a my-websocket-server.example.com -p 3004
```
For full documentation of command line switches read [readme](https://github.com/abeai/pino-webscoket#README)
For full documentation of command line switches read the [README](https://github.com/abeai/pino-websocket#readme).

View File

@ -55,7 +55,7 @@ app.get('/', function (req, res) {
app.listen(3000)
```
See the [pino-http readme](http://npm.im/pino-http) for more info.
See the [pino-http readme](https://npm.im/pino-http) for more info.
<a id="hapi"></a>
## Pino with Hapi
@ -117,7 +117,7 @@ start().catch((err) => {
})
```
See the [hapi-pino readme](http://npm.im/hapi-pino) for more info.
See the [hapi-pino readme](https://npm.im/hapi-pino) for more info.
<a id="restify"></a>
## Pino with Restify
@ -140,7 +140,7 @@ server.get('/', function (req, res) {
server.listen(3000)
```
See the [restify-pino-logger readme](http://npm.im/restify-pino-logger) for more info.
See the [restify-pino-logger readme](https://npm.im/restify-pino-logger) for more info.
<a id="koa"></a>
## Pino with Koa
@ -187,7 +187,7 @@ function handle (req, res) {
server.listen(3000)
```
See the [pino-http readme](http://npm.im/pino-http) for more info.
See the [pino-http readme](https://npm.im/pino-http) for more info.
<a id="nest"></a>
@ -226,4 +226,4 @@ async function bootstrap() {
bootstrap()
```
See the [nestjs-pino readme](http://npm.im/nestjs-pino) for more info.
See the [nestjs-pino readme](https://npm.im/nestjs-pino) for more info.

View File

@ -93,7 +93,7 @@ function setLevel (level) {
const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]
const hook = this[hooksSym].logMethod
for (var key in values) {
for (const key in values) {
if (levelVal > values[key]) {
this[key] = noop
continue
@ -123,10 +123,14 @@ function isLevelEnabled (logLevel) {
}
function mappings (customLevels = null, useOnlyCustomLevels = false) {
const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => {
o[customLevels[k]] = k
return o
}, {}) : null
const customNums = customLevels
/* eslint-disable */
? Object.keys(customLevels).reduce((o, k) => {
o[customLevels[k]] = k
return o
}, {})
: null
/* eslint-enable */
const labels = Object.assign(
Object.create(Object.prototype, { Infinity: { value: 'silent' } }),

View File

@ -81,16 +81,17 @@ function child (bindings) {
if (bindings.hasOwnProperty('serializers') === true) {
instance[serializersSym] = Object.create(null)
for (var k in serializers) {
for (const k in serializers) {
instance[serializersSym][k] = serializers[k]
}
const parentSymbols = Object.getOwnPropertySymbols(serializers)
/* eslint no-var: off */
for (var i = 0; i < parentSymbols.length; i++) {
const ks = parentSymbols[i]
instance[serializersSym][ks] = serializers[ks]
}
for (var bk in bindings.serializers) {
for (const bk in bindings.serializers) {
instance[serializersSym][bk] = bindings.serializers[bk]
}
const bindingsSymbols = Object.getOwnPropertySymbols(bindings.serializers)
@ -127,8 +128,8 @@ function child (bindings) {
function bindings () {
const chindings = this[chindingsSym]
var chindingsJson = `{${chindings.substr(1)}}` // at least contains ,"pid":7068,"hostname":"myMac"
var bindingsFromJson = JSON.parse(chindingsJson)
const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,"pid":7068,"hostname":"myMac"
const bindingsFromJson = JSON.parse(chindingsJson)
delete bindingsFromJson.pid
delete bindingsFromJson.hostname
return bindingsFromJson
@ -143,7 +144,7 @@ function setBindings (newBindings) {
function write (_obj, msg, num) {
const t = this[timeSym]()
const mixin = this[mixinSym]
var obj
let obj
if (_obj === undefined || _obj === null) {
obj = mixin ? mixin({}) : {}

View File

@ -85,9 +85,11 @@ function redaction (opts, serialize) {
if (shape[k] === null) {
o[k] = (value) => topCensor(value, [k])
} else {
const wrappedCensor = typeof censor === 'function' ? (value, path) => {
return censor(value, [k, ...path])
} : censor
const wrappedCensor = typeof censor === 'function'
? (value, path) => {
return censor(value, [k, ...path])
}
: censor
o[k] = fastRedact({
paths: shape[k],
censor: wrappedCensor,
@ -105,7 +107,7 @@ function handle (opts) {
validate(opts)
return opts
}
var { paths, censor = CENSOR, remove } = opts
let { paths, censor = CENSOR, remove } = opts
if (Array.isArray(paths) === false) { throw Error('pino redact must contain an array of strings') }
if (remove === true) censor = undefined
validate({ paths, censor })

View File

@ -31,12 +31,12 @@ function genLog (level, hook) {
if (!hook) return LOG
return function hookWrappedLog (...args) {
hook.call(this, args, LOG)
hook.call(this, args, LOG, level)
}
function LOG (o, ...n) {
if (typeof o === 'object') {
var msg = o
let msg = o
if (o !== null) {
if (o.method && o.headers && o.socket) {
o = mapHttpRequest(o)
@ -45,7 +45,7 @@ function genLog (level, hook) {
}
}
if (this[nestedKeySym]) o = { [this[nestedKeySym]]: o }
var formatParams
let formatParams
if (msg === null && n.length === 0) {
formatParams = [null]
} else {
@ -65,10 +65,10 @@ function genLog (level, hook) {
// 34 and 92 happens all the time, so we
// have a fast case for them
function asString (str) {
var result = ''
var last = 0
var found = false
var point = 255
let result = ''
let last = 0
let found = false
let point = 255
const l = str.length
if (l > 100) {
return JSON.stringify(str)
@ -97,14 +97,14 @@ function asJson (obj, msg, num, time) {
const serializers = this[serializersSym]
const formatters = this[formattersSym]
const messageKey = this[messageKeySym]
var data = this[lsCacheSym][num] + time
let data = this[lsCacheSym][num] + time
// we need the child bindings added to the output first so instance logged
// objects can take precedence when JSON.parse-ing the resulting log line
data = data + chindings
var value
var notHasOwnProperty = obj.hasOwnProperty === undefined
let value
const notHasOwnProperty = obj.hasOwnProperty === undefined
if (formatters.log) {
obj = formatters.log(obj)
}
@ -112,7 +112,7 @@ function asJson (obj, msg, num, time) {
obj[messageKey] = msg
}
const wildcardStringifier = stringifiers[wildcardFirstSym]
for (var key in obj) {
for (const key in obj) {
value = obj[key]
if ((notHasOwnProperty || obj.hasOwnProperty(key)) && value !== undefined) {
value = serializers[key] ? serializers[key](value) : value
@ -147,9 +147,8 @@ function asJson (obj, msg, num, time) {
}
function asChindings (instance, bindings) {
var key
var value
var data = instance[chindingsSym]
let value
let data = instance[chindingsSym]
const stringify = instance[stringifySym]
const stringifiers = instance[stringifiersSym]
const wildcardStringifier = stringifiers[wildcardFirstSym]
@ -157,7 +156,7 @@ function asChindings (instance, bindings) {
const formatter = instance[formattersSym].bindings
bindings = formatter(bindings)
for (key in bindings) {
for (const key in bindings) {
value = bindings[key]
const valid = key !== 'level' &&
key !== 'serializers' &&
@ -181,7 +180,7 @@ function getPrettyStream (opts, prettifier, dest, instance) {
return prettifierMetaWrapper(prettifier(opts), dest, opts)
}
try {
var prettyFactory = require('pino-pretty')
const prettyFactory = require('pino-pretty')
prettyFactory.asMetaWrapper = prettifierMetaWrapper
return prettifierMetaWrapper(prettyFactory(opts), dest, opts)
} catch (e) {
@ -191,7 +190,7 @@ function getPrettyStream (opts, prettifier, dest, instance) {
function prettifierMetaWrapper (pretty, dest, opts) {
opts = Object.assign({ suppressFlushSyncWarning: false }, opts)
var warned = false
let warned = false
return {
[needsMetadataGsym]: true,
lastLevel: 0,
@ -212,7 +211,7 @@ function prettifierMetaWrapper (pretty, dest, opts) {
},
chindings () {
const lastLogger = this.lastLogger
var chindings = null
let chindings = null
// protection against flushSync being called before logging
// anything
@ -233,7 +232,7 @@ function prettifierMetaWrapper (pretty, dest, opts) {
const lastLogger = this.lastLogger
const chindings = this.chindings()
var time = this.lastTime
let time = this.lastTime
if (time.match(/^\d+/)) {
time = parseInt(time)
@ -241,9 +240,9 @@ function prettifierMetaWrapper (pretty, dest, opts) {
time = time.slice(1, -1)
}
var lastObj = this.lastObj
var lastMsg = this.lastMsg
var errorProps = null
const lastObj = this.lastObj
const lastMsg = this.lastMsg
const errorProps = null
const formatters = lastLogger[formattersSym]
const formattedObj = formatters.log ? formatters.log(lastObj) : lastObj
@ -260,16 +259,15 @@ function prettifierMetaWrapper (pretty, dest, opts) {
const serializers = lastLogger[serializersSym]
const keys = Object.keys(serializers)
var key
for (var i = 0; i < keys.length; i++) {
key = keys[i]
const key = keys[i]
if (obj[key] !== undefined) {
obj[key] = serializers[key](obj[key])
}
}
for (key in chindings) {
for (const key in chindings) {
if (!obj.hasOwnProperty(key)) {
obj[key] = chindings[key]
}

View File

@ -1,6 +1,6 @@
{
"name": "pino",
"version": "6.8.0",
"version": "6.11.2",
"description": "super fast, all natural json logger",
"main": "pino.js",
"browser": "./browser.js",
@ -18,7 +18,9 @@
"scripts": {
"docs": "docsify serve",
"browser-test": "airtap --local 8080 test/browser*test.js",
"test": "standard | snazzy && tap --100 test/*test.js test/*/*test.js",
"lint": "eslint .",
"test": "npm run lint && tap --100 test/*test.js test/*/*test.js",
"test-ci": "npm run lint && tap test/*test.js test/*/*test.js --coverage-report=lcovonly",
"cov-ui": "tap --coverage-report=html test/*test.js test/*/*test.js",
"bench": "node benchmarks/utils/runbench all",
"bench-basic": "node benchmarks/utils/runbench basic",
@ -58,12 +60,17 @@
},
"homepage": "http://getpino.io",
"devDependencies": {
"airtap": "3.0.0",
"airtap": "4.0.3",
"benchmark": "^2.1.4",
"bole": "^4.0.0",
"bunyan": "^1.8.14",
"docsify-cli": "^4.4.1",
"execa": "^4.0.0",
"eslint": "^7.17.0",
"eslint-config-standard": "^16.0.2",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"execa": "^5.0.0",
"fastbench": "^1.0.1",
"flush-write-stream": "^2.0.0",
"import-fresh": "^3.2.1",
@ -74,12 +81,10 @@
"proxyquire": "^2.1.3",
"pump": "^3.0.0",
"semver": "^7.0.0",
"snazzy": "^8.0.0",
"split2": "^3.1.1",
"standard": "^14.3.3",
"steed": "^1.1.3",
"strip-ansi": "^6.0.0",
"tap": "^14.10.8",
"tap": "^15.0.1",
"tape": "^5.0.0",
"through2": "^4.0.0",
"winston": "^3.3.3"
@ -88,8 +93,8 @@
"fast-redact": "^3.0.0",
"fast-safe-stringify": "^2.0.7",
"flatstr": "^1.0.12",
"pino-std-serializers": "^2.4.2",
"quick-format-unescaped": "^4.0.1",
"pino-std-serializers": "^3.1.0",
"quick-format-unescaped": "^4.0.3",
"sonic-boom": "^1.0.2"
}
}

15
pino.js
View File

@ -138,10 +138,19 @@ function pino (...args) {
[stringifySym]: stringify,
[formattersSym]: allFormatters
})
const chindings = base === null ? '' : (name === undefined)
? coreChindings(base) : coreChindings(Object.assign({}, base, { name }))
let chindings = ''
if (base !== null) {
if (name === undefined) {
chindings = coreChindings(base)
} else {
chindings = coreChindings(Object.assign({}, base, { name }))
}
}
const time = (timestamp instanceof Function)
? timestamp : (timestamp ? epochTime : nullTime)
? timestamp
: (timestamp ? epochTime : nullTime)
const timeSliceIndex = time().indexOf(':') + 1
if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')

View File

@ -9,18 +9,18 @@ const { version } = require('../package.json')
const { pid } = process
const hostname = os.hostname()
test('pino version is exposed on export', async ({ is }) => {
is(pino.version, version)
test('pino version is exposed on export', async ({ equal }) => {
equal(pino.version, version)
})
test('pino version is exposed on instance', async ({ is }) => {
test('pino version is exposed on instance', async ({ equal }) => {
const instance = pino()
is(instance.version, version)
equal(instance.version, version)
})
test('child instance exposes pino version', async ({ is }) => {
test('child instance exposes pino version', async ({ equal }) => {
const child = pino().child({ foo: 'bar' })
is(child.version, version)
equal(child.version, version)
})
test('bindings are exposed on every instance', async ({ same }) => {
@ -67,15 +67,15 @@ test('child should not share bindings of parent set after child creation', async
})
function levelTest (name, level) {
test(`${name} logs as ${level}`, async ({ is }) => {
test(`${name} logs as ${level}`, async ({ equal }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
instance[name]('hello world')
check(is, await once(stream, 'data'), level, 'hello world')
check(equal, await once(stream, 'data'), level, 'hello world')
})
test(`passing objects at level ${name}`, async ({ is, same }) => {
test(`passing objects at level ${name}`, async ({ equal, same }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
@ -83,22 +83,22 @@ function levelTest (name, level) {
instance[name](obj)
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
is(result.pid, pid)
is(result.hostname, hostname)
is(result.level, level)
is(result.hello, 'world')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(result.pid, pid)
equal(result.hostname, hostname)
equal(result.level, level)
equal(result.hello, 'world')
same(Object.keys(obj), ['hello'])
})
test(`passing an object and a string at level ${name}`, async ({ is, same }) => {
test(`passing an object and a string at level ${name}`, async ({ equal, same }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
const obj = { hello: 'world' }
instance[name](obj, 'a string')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -110,13 +110,13 @@ function levelTest (name, level) {
same(Object.keys(obj), ['hello'])
})
test(`overriding object key by string at level ${name}`, async ({ is, same }) => {
test(`overriding object key by string at level ${name}`, async ({ equal, same }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
instance[name]({ hello: 'world', msg: 'object' }, 'string')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -127,16 +127,16 @@ function levelTest (name, level) {
})
})
test(`formatting logs as ${name}`, async ({ is }) => {
test(`formatting logs as ${name}`, async ({ equal }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
instance[name]('hello %d', 42)
const result = await once(stream, 'data')
check(is, result, level, 'hello 42')
check(equal, result, level, 'hello 42')
})
test(`formatting a symbol at level ${name}`, async ({ is }) => {
test(`formatting a symbol at level ${name}`, async ({ equal }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
@ -146,10 +146,10 @@ function levelTest (name, level) {
const result = await once(stream, 'data')
check(is, result, level, 'hello Symbol(foo)')
check(equal, result, level, 'hello Symbol(foo)')
})
test(`passing error with a serializer at level ${name}`, async ({ is, same }) => {
test(`passing error with a serializer at level ${name}`, async ({ equal, same }) => {
const stream = sink()
const err = new Error('myerror')
const instance = pino({
@ -160,7 +160,7 @@ function levelTest (name, level) {
instance.level = name
instance[name]({ err })
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -175,14 +175,14 @@ function levelTest (name, level) {
})
})
test(`child logger for level ${name}`, async ({ is, same }) => {
test(`child logger for level ${name}`, async ({ equal, same }) => {
const stream = sink()
const instance = pino(stream)
instance.level = name
const child = instance.child({ hello: 'world' })
child[name]('hello world')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -201,7 +201,7 @@ levelTest('info', 30)
levelTest('debug', 20)
levelTest('trace', 10)
test('serializers can return undefined to strip field', async ({ is }) => {
test('serializers can return undefined to strip field', async ({ equal }) => {
const stream = sink()
const instance = pino({
serializers: {
@ -211,7 +211,7 @@ test('serializers can return undefined to strip field', async ({ is }) => {
instance.info({ test: 'sensitive info' })
const result = await once(stream, 'data')
is('test' in result, false)
equal('test' in result, false)
})
test('does not explode with a circular ref', async ({ doesNotThrow }) => {
@ -225,14 +225,14 @@ test('does not explode with a circular ref', async ({ doesNotThrow }) => {
doesNotThrow(() => instance.info(a))
})
test('set the name', async ({ is, same }) => {
test('set the name', async ({ equal, same }) => {
const stream = sink()
const instance = pino({
name: 'hello'
}, stream)
instance.fatal('this is fatal')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -243,7 +243,7 @@ test('set the name', async ({ is, same }) => {
})
})
test('set the messageKey', async ({ is, same }) => {
test('set the messageKey', async ({ equal, same }) => {
const stream = sink()
const message = 'hello world'
const messageKey = 'fooMessage'
@ -252,7 +252,7 @@ test('set the messageKey', async ({ is, same }) => {
}, stream)
instance.info(message)
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -262,7 +262,7 @@ test('set the messageKey', async ({ is, same }) => {
})
})
test('set the nestedKey', async ({ is, same }) => {
test('set the nestedKey', async ({ equal, same }) => {
const stream = sink()
const object = { hello: 'world' }
const nestedKey = 'stuff'
@ -271,7 +271,7 @@ test('set the nestedKey', async ({ is, same }) => {
}, stream)
instance.info(object)
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -281,12 +281,12 @@ test('set the nestedKey', async ({ is, same }) => {
})
})
test('set undefined properties', async ({ is, same }) => {
test('set undefined properties', async ({ equal, same }) => {
const stream = sink()
const instance = pino(stream)
instance.info({ hello: 'world', property: undefined })
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
pid,
@ -296,15 +296,15 @@ test('set undefined properties', async ({ is, same }) => {
})
})
test('prototype properties are not logged', async ({ is }) => {
test('prototype properties are not logged', async ({ equal }) => {
const stream = sink()
const instance = pino(stream)
instance.info(Object.create({ hello: 'world' }))
const { hello } = await once(stream, 'data')
is(hello, undefined)
equal(hello, undefined)
})
test('set the base', async ({ is, same }) => {
test('set the base', async ({ equal, same }) => {
const stream = sink()
const instance = pino({
base: {
@ -314,7 +314,7 @@ test('set the base', async ({ is, same }) => {
instance.fatal('this is fatal')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
a: 'b',
@ -323,14 +323,14 @@ test('set the base', async ({ is, same }) => {
})
})
test('set the base to null', async ({ is, same }) => {
test('set the base to null', async ({ equal, same }) => {
const stream = sink()
const instance = pino({
base: null
}, stream)
instance.fatal('this is fatal')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
level: 60,
@ -338,7 +338,7 @@ test('set the base to null', async ({ is, same }) => {
})
})
test('set the base to null and use a formatter', async ({ is, same }) => {
test('set the base to null and use a formatter', async ({ equal, same }) => {
const stream = sink()
const instance = pino({
base: null,
@ -350,7 +350,7 @@ test('set the base to null and use a formatter', async ({ is, same }) => {
}, stream)
instance.fatal('this is fatal too')
const result = await once(stream, 'data')
is(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
equal(new Date(result.time) <= new Date(), true, 'time is greater than Date.now()')
delete result.time
same(result, {
level: 60,
@ -359,14 +359,14 @@ test('set the base to null and use a formatter', async ({ is, same }) => {
})
})
test('throw if creating child without bindings', async ({ is, fail }) => {
test('throw if creating child without bindings', async ({ equal, fail }) => {
const stream = sink()
const instance = pino(stream)
try {
instance.child()
fail('it should throw')
} catch (err) {
is(err.message, 'missing bindings for child Pino')
equal(err.message, 'missing bindings for child Pino')
}
})
@ -436,14 +436,14 @@ test('object and format string property', async ({ same }) => {
})
})
test('correctly strip undefined when returned from toJSON', async ({ is }) => {
test('correctly strip undefined when returned from toJSON', async ({ equal }) => {
const stream = sink()
const instance = pino({
test: 'this'
}, stream)
instance.fatal({ test: { toJSON () { return undefined } } })
const result = await once(stream, 'data')
is('test' in result, false)
equal('test' in result, false)
})
test('correctly supports stderr', async ({ same }) => {
@ -585,16 +585,16 @@ test('does not override opts with a string as second argument', async ({ same })
})
// https://github.com/pinojs/pino/issues/222
test('children with same names render in correct order', async ({ is }) => {
test('children with same names render in correct order', async ({ equal }) => {
const stream = sink()
const root = pino(stream)
root.child({ a: 1 }).child({ a: 2 }).info({ a: 3 })
const { a } = await once(stream, 'data')
is(a, 3, 'last logged object takes precedence')
equal(a, 3, 'last logged object takes precedence')
})
// https://github.com/pinojs/pino/pull/251 - use this.stringify
test('use `fast-safe-stringify` to avoid circular dependencies', async ({ deepEqual }) => {
test('use `fast-safe-stringify` to avoid circular dependencies', async ({ same }) => {
const stream = sink()
const root = pino(stream)
// circular depth
@ -602,7 +602,7 @@ test('use `fast-safe-stringify` to avoid circular dependencies', async ({ deepEq
obj.a = obj
root.info(obj)
const { a } = await once(stream, 'data')
deepEqual(a, { a: '[Circular]' })
same(a, { a: '[Circular]' })
})
test('fast-safe-stringify must be used when interpolating', async (t) => {
@ -614,10 +614,10 @@ test('fast-safe-stringify must be used when interpolating', async (t) => {
instance.info('test %j', o)
const { msg } = await once(stream, 'data')
t.is(msg, 'test {"a":{"b":{"c":"[Circular]"}}}')
t.equal(msg, 'test {"a":{"b":{"c":"[Circular]"}}}')
})
test('throws when setting useOnlyCustomLevels without customLevels', async ({ is, throws }) => {
test('throws when setting useOnlyCustomLevels without customLevels', async ({ equal, throws }) => {
throws(() => {
pino({
useOnlyCustomLevels: true
@ -628,7 +628,7 @@ test('throws when setting useOnlyCustomLevels without customLevels', async ({ is
useOnlyCustomLevels: true
})
} catch ({ message }) {
is(message, 'customLevels is required if useOnlyCustomLevels is set true')
equal(message, 'customLevels is required if useOnlyCustomLevels is set true')
}
})
@ -640,7 +640,7 @@ test('correctly log Infinity', async (t) => {
instance.info(o)
const { num } = await once(stream, 'data')
t.is(num, null)
t.equal(num, null)
})
test('correctly log -Infinity', async (t) => {
@ -651,7 +651,7 @@ test('correctly log -Infinity', async (t) => {
instance.info(o)
const { num } = await once(stream, 'data')
t.is(num, null)
t.equal(num, null)
})
test('correctly log NaN', async (t) => {
@ -662,14 +662,14 @@ test('correctly log NaN', async (t) => {
instance.info(o)
const { num } = await once(stream, 'data')
t.is(num, null)
t.equal(num, null)
})
test('offers a .default() method to please typescript', async ({ is }) => {
is(pino.default, pino)
test('offers a .default() method to please typescript', async ({ equal }) => {
equal(pino.default, pino)
const stream = sink()
const instance = pino.default(stream)
instance.info('hello world')
check(is, await once(stream, 'data'), 30, 'hello world')
check(equal, await once(stream, 'data'), 30, 'hello world')
})

View File

@ -8,14 +8,14 @@ const pino = require('..')
function test (file) {
file = join('fixtures', 'broken-pipe', file)
t.test(file, { parallel: true }, async ({ is }) => {
t.test(file, { parallel: true }, async ({ equal }) => {
const child = fork(join(__dirname, file), { silent: true })
child.stdout.destroy()
child.stderr.pipe(process.stdout)
const res = await once(child, 'close')
is(res, 0) // process exits successfully
equal(res, 0) // process exits successfully
})
}
@ -25,7 +25,7 @@ test('basic.js')
test('destination.js')
test('syncfalse.js')
t.test('let error pass through', ({ is, plan }) => {
t.test('let error pass through', ({ equal, plan }) => {
plan(3)
const stream = pino.destination()
@ -37,6 +37,6 @@ t.test('let error pass through', ({ is, plan }) => {
process.nextTick(() => stream.emit('error', new Error('kaboom')))
stream.on('error', (err) => {
is(err.message, 'kaboom')
equal(err.message, 'kaboom')
})
})

View File

@ -218,7 +218,7 @@ if (process.title !== 'browser') {
}
test('child does not overwrite parent serializers', ({ end, is }) => {
var c = 0
let c = 0
const parent = pino({
serializers: parentSerializers,
browser: {
@ -290,7 +290,7 @@ test('children serializers get called when inherited from parent', ({ end, is })
end()
})
test('non overriden serializers are available in the children', ({ end, is }) => {
test('non overridden serializers are available in the children', ({ end, is }) => {
const pSerializers = {
onlyParent: () => 'parent',
shared: () => 'parent'
@ -301,7 +301,7 @@ test('non overriden serializers are available in the children', ({ end, is }) =>
onlyChild: () => 'child'
}
var c = 0
let c = 0
const parent = pino({
serializers: pSerializers,

View File

@ -17,7 +17,7 @@ test('throws if transmit object does not have send function', ({ end, throws })
})
test('calls send function after write', ({ end, is }) => {
var c = 0
let c = 0
const logger = pino({
browser: {
write: () => {
@ -124,10 +124,10 @@ test('passes send function message objects in logEvent object when asObject is s
})
test('supplies a timestamp (ts) in logEvent object which is exactly the same as the `time` property in asObject mode', ({ end, is }) => {
var expected
let expected
const logger = pino({
browser: {
asObject: true, // implict because `write`, but just to be explicit
asObject: true, // implicit because `write`, but just to be explicit
write (o) {
expected = o.time
},
@ -188,7 +188,7 @@ test('passes send function level:{label, value} via logEvent object', ({ end, is
})
test('calls send function according to transmit.level', ({ end, is }) => {
var c = 0
let c = 0
const logger = pino({
browser: {
write: noop,
@ -209,7 +209,7 @@ test('calls send function according to transmit.level', ({ end, is }) => {
})
test('transmit.level defaults to logger level', ({ end, is }) => {
var c = 0
let c = 0
const logger = pino({
level: 'error',
browser: {
@ -230,7 +230,7 @@ test('transmit.level defaults to logger level', ({ end, is }) => {
})
test('transmit.level is effective even if lower than logger level', ({ end, is }) => {
var c = 0
let c = 0
const logger = pino({
level: 'error',
browser: {
@ -312,8 +312,8 @@ test('applies all serializers to messages and bindings (serialize:true)', ({ end
})
test('extracts correct bindings and raw messages over multiple transmits', ({ end, same, is }) => {
var messages = null
var bindings = null
let messages = null
let bindings = null
const logger = pino({
browser: {

View File

@ -133,7 +133,7 @@ absentConsoleMethodTest('trace', 'log')
// do not run this with airtap
if (process.title !== 'browser') {
test('in absence of console, log methods become noops', ({ end, ok }) => {
var console = global.console
const console = global.console
delete global.console
const instance = fresh('../browser')()
global.console = console
@ -149,7 +149,7 @@ if (process.title !== 'browser') {
}
test('opts.browser.asObject logs pino-like object to console', ({ end, ok, is }) => {
var info = console.info
const info = console.info
console.info = function (o) {
is(o.level, 30)
is(o.msg, 'test')
@ -388,7 +388,7 @@ test('opts.browser.asObject defensively mitigates naughty numbers', ({ end, pass
})
test('opts.browser.write obj falls back to console where a method is not supplied', ({ end, ok, is }) => {
var info = console.info
const info = console.info
console.info = (o) => {
is(o.level, 30)
is(o.msg, 'test')
@ -414,7 +414,7 @@ test('opts.browser.write obj falls back to console where a method is not supplie
function levelTest (name) {
test(name + ' logs', ({ end, is }) => {
var msg = 'hello world'
const msg = 'hello world'
sink(name, (args) => {
is(args[0], msg)
end()
@ -423,7 +423,7 @@ function levelTest (name) {
})
test('passing objects at level ' + name, ({ end, is }) => {
var msg = { hello: 'world' }
const msg = { hello: 'world' }
sink(name, (args) => {
is(args[0], msg)
end()
@ -432,8 +432,8 @@ function levelTest (name) {
})
test('passing an object and a string at level ' + name, ({ end, is }) => {
var a = { hello: 'world' }
var b = 'a string'
const a = { hello: 'world' }
const b = 'a string'
sink(name, (args) => {
is(args[0], a)
is(args[1], b)
@ -452,7 +452,7 @@ function levelTest (name) {
})
test('passing error at level ' + name, ({ end, is }) => {
var err = new Error('myerror')
const err = new Error('myerror')
sink(name, (args) => {
is(args[0], err)
end()
@ -462,7 +462,7 @@ function levelTest (name) {
test('passing error with a serializer at level ' + name, ({ end, is }) => {
// in browser - should have no effect (should not crash)
var err = new Error('myerror')
const err = new Error('myerror')
sink(name, (args) => {
is(args[0].err, err)
end()
@ -477,8 +477,8 @@ function levelTest (name) {
})
test('child logger for level ' + name, ({ end, is }) => {
var msg = 'hello world'
var parent = { hello: 'world' }
const msg = 'hello world'
const parent = { hello: 'world' }
sink(name, (args) => {
is(args[0], parent)
is(args[1], msg)
@ -490,9 +490,9 @@ function levelTest (name) {
})
test('child-child logger for level ' + name, ({ end, is }) => {
var msg = 'hello world'
var grandParent = { hello: 'world' }
var parent = { hello: 'you' }
const msg = 'hello world'
const grandParent = { hello: 'world' }
const parent = { hello: 'you' }
sink(name, (args) => {
is(args[0], grandParent)
is(args[1], parent)
@ -519,7 +519,7 @@ function consoleMethodTest (level, method) {
function absentConsoleMethodTest (method, fallback) {
test('in absence of console.' + method + ', console.' + fallback + ' is used', ({ end, is }) => {
var fn = console[method]
const fn = console[method]
console[method] = undefined
sink(fallback, function (args) {
is(args[0], 'test')
@ -533,13 +533,13 @@ function absentConsoleMethodTest (method, fallback) {
function isFunc (fn) { return typeof fn === 'function' }
function fnName (fn) {
var rx = /^\s*function\s*([^(]*)/i
var match = rx.exec(fn)
const rx = /^\s*function\s*([^(]*)/i
const match = rx.exec(fn)
return match && match[1]
}
function sink (method, fn) {
if (method === 'fatal') method = 'error'
var orig = console[method]
const orig = console[method]
console[method] = function () {
console[method] = orig
fn(Array.prototype.slice.call(arguments))

View File

@ -10,7 +10,7 @@ const pino = require('../')
process.removeAllListeners('warning')
process.on('warning', () => {})
test('adds additional levels', async ({ is }) => {
test('adds additional levels', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -21,10 +21,10 @@ test('adds additional levels', async ({ is }) => {
logger.foo('test')
const { level } = await once(stream, 'data')
is(level, 35)
equal(level, 35)
})
test('custom levels does not override default levels', async ({ is }) => {
test('custom levels does not override default levels', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -34,10 +34,10 @@ test('custom levels does not override default levels', async ({ is }) => {
logger.info('test')
const { level } = await once(stream, 'data')
is(level, 30)
equal(level, 30)
})
test('default levels can be redefined using custom levels', async ({ is }) => {
test('default levels can be redefined using custom levels', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -47,14 +47,14 @@ test('default levels can be redefined using custom levels', async ({ is }) => {
useOnlyCustomLevels: true
}, stream)
is(logger.hasOwnProperty('info'), true)
equal(logger.hasOwnProperty('info'), true)
logger.info('test')
const { level } = await once(stream, 'data')
is(level, 35)
equal(level, 35)
})
test('custom levels overrides default level label if use useOnlyCustomLevels', async ({ is }) => {
test('custom levels overrides default level label if use useOnlyCustomLevels', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -64,10 +64,10 @@ test('custom levels overrides default level label if use useOnlyCustomLevels', a
level: 'foo'
}, stream)
is(logger.hasOwnProperty('info'), false)
equal(logger.hasOwnProperty('info'), false)
})
test('custom levels overrides default level value if use useOnlyCustomLevels', async ({ is }) => {
test('custom levels overrides default level value if use useOnlyCustomLevels', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -77,10 +77,10 @@ test('custom levels overrides default level value if use useOnlyCustomLevels', a
level: 35
}, stream)
is(logger.hasOwnProperty('info'), false)
equal(logger.hasOwnProperty('info'), false)
})
test('custom levels are inherited by children', async ({ is }) => {
test('custom levels are inherited by children', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -90,12 +90,12 @@ test('custom levels are inherited by children', async ({ is }) => {
logger.child({ childMsg: 'ok' }).foo('test')
const { msg, childMsg, level } = await once(stream, 'data')
is(level, 35)
is(childMsg, 'ok')
is(msg, 'test')
equal(level, 35)
equal(childMsg, 'ok')
equal(msg, 'test')
})
test('custom levels can be specified on child bindings', async ({ is }) => {
test('custom levels can be specified on child bindings', async ({ equal }) => {
const stream = sink()
const logger = pino(stream).child({
customLevels: {
@ -106,12 +106,12 @@ test('custom levels can be specified on child bindings', async ({ is }) => {
logger.foo('test')
const { msg, childMsg, level } = await once(stream, 'data')
is(level, 35)
is(childMsg, 'ok')
is(msg, 'test')
equal(level, 35)
equal(childMsg, 'ok')
equal(msg, 'test')
})
test('customLevels property child bindings does not get logged', async ({ is }) => {
test('customLevels property child bindings does not get logged', async ({ equal }) => {
const stream = sink()
const logger = pino(stream).child({
customLevels: {
@ -122,10 +122,10 @@ test('customLevels property child bindings does not get logged', async ({ is })
logger.foo('test')
const { customLevels } = await once(stream, 'data')
is(customLevels, undefined)
equal(customLevels, undefined)
})
test('throws when specifying pre-existing parent labels via child bindings', async ({ is, throws }) => {
test('throws when specifying pre-existing parent labels via child bindings', async ({ equal, throws }) => {
const stream = sink()
throws(() => pino({
customLevels: {
@ -148,11 +148,11 @@ test('throws when specifying pre-existing parent labels via child bindings', asy
}
})
} catch ({ message }) {
is(message, 'levels cannot be overridden')
equal(message, 'levels cannot be overridden')
}
})
test('throws when specifying pre-existing parent values via child bindings', async ({ is, throws }) => {
test('throws when specifying pre-existing parent values via child bindings', async ({ equal, throws }) => {
const stream = sink()
throws(() => pino({
customLevels: {
@ -175,11 +175,11 @@ test('throws when specifying pre-existing parent values via child bindings', asy
}
})
} catch ({ message }) {
is(message, 'pre-existing level values cannot be used for new levels')
equal(message, 'pre-existing level values cannot be used for new levels')
}
})
test('throws when specifying core values via child bindings', async ({ is, throws }) => {
test('throws when specifying core values via child bindings', async ({ equal, throws }) => {
const stream = sink()
throws(() => pino(stream).child({
customLevels: {
@ -194,11 +194,11 @@ test('throws when specifying core values via child bindings', async ({ is, throw
}
})
} catch ({ message }) {
is(message, 'pre-existing level values cannot be used for new levels')
equal(message, 'pre-existing level values cannot be used for new levels')
}
})
test('throws when useOnlyCustomLevels is set true without customLevels', async ({ is, throws }) => {
test('throws when useOnlyCustomLevels is set true without customLevels', async ({ equal, throws }) => {
const stream = sink()
throws(() => pino({
useOnlyCustomLevels: true
@ -209,37 +209,37 @@ test('throws when useOnlyCustomLevels is set true without customLevels', async (
useOnlyCustomLevels: true
}, stream)
} catch ({ message }) {
is(message, 'customLevels is required if useOnlyCustomLevels is set true')
equal(message, 'customLevels is required if useOnlyCustomLevels is set true')
}
})
test('custom level on one instance does not affect other instances', async ({ is }) => {
test('custom level on one instance does not affect other instances', async ({ equal }) => {
pino({
customLevels: {
foo: 37
}
})
is(typeof pino().foo, 'undefined')
equal(typeof pino().foo, 'undefined')
})
test('setting level below or at custom level will successfully log', async ({ is }) => {
test('setting level below or at custom level will successfully log', async ({ equal }) => {
const stream = sink()
const instance = pino({ customLevels: { foo: 35 } }, stream)
instance.level = 'foo'
instance.info('nope')
instance.foo('bar')
const { msg } = await once(stream, 'data')
is(msg, 'bar')
equal(msg, 'bar')
})
test('custom level below level threshold will not log', async ({ is }) => {
test('custom level below level threshold will not log', async ({ equal }) => {
const stream = sink()
const instance = pino({ customLevels: { foo: 15 } }, stream)
instance.level = 'info'
instance.info('bar')
instance.foo('nope')
const { msg } = await once(stream, 'data')
is(msg, 'bar')
equal(msg, 'bar')
})
test('does not share custom level state across siblings', async ({ doesNotThrow }) => {
@ -255,7 +255,7 @@ test('does not share custom level state across siblings', async ({ doesNotThrow
})
})
test('custom level does not affect the levels serializer', async ({ is }) => {
test('custom level does not affect the levels serializer', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -271,10 +271,10 @@ test('custom level does not affect the levels serializer', async ({ is }) => {
logger.foo('test')
const { priority } = await once(stream, 'data')
is(priority, 35)
equal(priority, 35)
})
test('When useOnlyCustomLevels is set to true, the level formatter should only get custom levels', async ({ is }) => {
test('When useOnlyCustomLevels is set to true, the level formatter should only get custom levels', async ({ equal }) => {
const stream = sink()
const logger = pino({
customLevels: {
@ -284,8 +284,8 @@ test('When useOnlyCustomLevels is set to true, the level formatter should only g
level: 42,
formatters: {
level (label, number) {
is(label, 'answer')
is(number, 42)
equal(label, 'answer')
equal(number, 42)
return { level: number }
}
}
@ -293,10 +293,10 @@ test('When useOnlyCustomLevels is set to true, the level formatter should only g
logger.answer('test')
const { level } = await once(stream, 'data')
is(level, 42)
equal(level, 42)
})
test('custom levels accesible in prettifier function', async ({ plan, same }) => {
test('custom levels accessible in prettifier function', async ({ plan, same }) => {
plan(1)
const logger = pino({
prettyPrint: true,

View File

@ -7,10 +7,10 @@ const pino = require('../')
process.removeAllListeners('warning')
test('useLevelLabels', async ({ match, is }) => {
test('useLevelLabels', async ({ match, equal }) => {
process.on('warning', onWarning)
function onWarning (warn) {
is(warn.code, 'PINODEP001')
equal(warn.code, 'PINODEP001')
}
const stream = sink()
@ -24,10 +24,10 @@ test('useLevelLabels', async ({ match, is }) => {
process.removeListener('warning', onWarning)
})
test('changeLevelName', async ({ match, is }) => {
test('changeLevelName', async ({ match, equal }) => {
process.on('warning', onWarning)
function onWarning (warn) {
is(warn.code, 'PINODEP002')
equal(warn.code, 'PINODEP002')
}
const stream = sink()
@ -41,10 +41,10 @@ test('changeLevelName', async ({ match, is }) => {
process.removeListener('warning', onWarning)
})
test('levelKey', async ({ match, is }) => {
test('levelKey', async ({ match, equal }) => {
process.on('warning', onWarning)
function onWarning (warn) {
is(warn.code, 'PINODEP002')
equal(warn.code, 'PINODEP002')
}
const stream = sink()
@ -58,11 +58,11 @@ test('levelKey', async ({ match, is }) => {
process.removeListener('warning', onWarning)
})
test('useLevelLabels and changeLevelName', async ({ match, is }) => {
test('useLevelLabels and changeLevelName', async ({ match, equal }) => {
let count = 0
process.on('warning', onWarning)
function onWarning (warn) {
is(warn.code, count === 0 ? 'PINODEP001' : 'PINODEP002')
equal(warn.code, count === 0 ? 'PINODEP001' : 'PINODEP002')
count += 1
}
@ -78,10 +78,10 @@ test('useLevelLabels and changeLevelName', async ({ match, is }) => {
process.removeListener('warning', onWarning)
})
test('pino.* serializer', async ({ match, is, pass }) => {
test('pino.* serializer', async ({ match, equal, pass }) => {
process.on('warning', onWarning)
function onWarning (warn) {
is(warn.code, 'PINODEP003')
equal(warn.code, 'PINODEP003')
}
const stream = sink()

View File

@ -137,9 +137,9 @@ test('an error with statusCode property is not confused for a http response', as
test('stack is omitted if it is not set on err', t => {
t.plan(2)
var err = new Error('myerror')
const err = new Error('myerror')
delete err.stack
var instance = pino(sink(function (chunk, enc, cb) {
const instance = pino(sink(function (chunk, enc, cb) {
t.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
t.equal(chunk.hasOwnProperty('stack'), false)
@ -152,9 +152,9 @@ test('stack is omitted if it is not set on err', t => {
test('stack is rendered as any other property if it\'s not a string', t => {
t.plan(3)
var err = new Error('myerror')
const err = new Error('myerror')
err.stack = null
var instance = pino(sink(function (chunk, enc, cb) {
const instance = pino(sink(function (chunk, enc, cb) {
t.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
t.equal(chunk.err.hasOwnProperty('stack'), true)

View File

@ -4,9 +4,9 @@ import helper from '../helper.js'
const { sink, check, once } = helper
t.test('esm support', async ({ is }) => {
t.test('esm support', async ({ equal }) => {
const stream = sink()
const instance = pino(stream)
instance.info('hello world')
check(is, await once(stream, 'data'), 30, 'hello world')
check(equal, await once(stream, 'data'), 30, 'hello world')
})

View File

@ -5,11 +5,11 @@ import { pino, destination } from '../../pino.js'
import { join } from 'path'
import { readFileSync } from 'fs'
t.test('named exports support', async ({ is }) => {
t.test('named exports support', async ({ equal }) => {
const stream = sink()
const instance = pino(stream)
instance.info('hello world')
check(is, await once(stream, 'data'), 30, 'hello world')
check(equal, await once(stream, 'data'), 30, 'hello world')
})
t.test('destination', async ({ same }) => {

View File

@ -7,8 +7,8 @@ const writer = require('flush-write-stream')
const { once } = require('./helper')
// https://github.com/pinojs/pino/issues/542
test('pino.destination log everything when calling process.exit(0)', async ({ isNot }) => {
var actual = ''
test('pino.destination log everything when calling process.exit(0)', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'destination-exit.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -18,12 +18,12 @@ test('pino.destination log everything when calling process.exit(0)', async ({ is
await once(child, 'close')
isNot(actual.match(/hello/), null)
isNot(actual.match(/world/), null)
not(actual.match(/hello/), null)
not(actual.match(/world/), null)
})
test('pino with no args log everything when calling process.exit(0)', async ({ isNot }) => {
var actual = ''
test('pino with no args log everything when calling process.exit(0)', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'default-exit.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -33,12 +33,12 @@ test('pino with no args log everything when calling process.exit(0)', async ({ i
await once(child, 'close')
isNot(actual.match(/hello/), null)
isNot(actual.match(/world/), null)
not(actual.match(/hello/), null)
not(actual.match(/world/), null)
})
test('sync false does not log everything when calling process.exit(0)', async ({ is }) => {
var actual = ''
test('sync false does not log everything when calling process.exit(0)', async ({ equal }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'syncfalse-exit.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -48,12 +48,12 @@ test('sync false does not log everything when calling process.exit(0)', async ({
await once(child, 'close')
is(actual.match(/hello/), null)
is(actual.match(/world/), null)
equal(actual.match(/hello/), null)
equal(actual.match(/world/), null)
})
test('sync false logs everything when calling flushSync', async ({ isNot }) => {
var actual = ''
test('sync false logs everything when calling flushSync', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'syncfalse-flush-exit.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -63,6 +63,6 @@ test('sync false logs everything when calling flushSync', async ({ isNot }) => {
await once(child, 'close')
isNot(actual.match(/hello/), null)
isNot(actual.match(/world/), null)
not(actual.match(/hello/), null)
not(actual.match(/world/), null)
})

View File

@ -38,13 +38,13 @@ test('throws if not supplied logger with pino.destination instance with sync fal
})
})
test('returns an exit listener function', async ({ is }) => {
is(typeof pino.final(pino(pino.destination({ sync: false })), () => {}), 'function')
test('returns an exit listener function', async ({ equal }) => {
equal(typeof pino.final(pino(pino.destination({ sync: false })), () => {}), 'function')
})
test('listener function immediately sync flushes when fired (sync false)', async ({ pass, fail }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: false })
var passed = false
let passed = false
dest.flushSync = () => {
passed = true
pass('flushSync called')
@ -56,7 +56,7 @@ test('listener function immediately sync flushes when fired (sync false)', async
test('listener function immediately sync flushes when fired (sync true)', async ({ pass, fail }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: true })
var passed = false
let passed = false
dest.flushSync = () => {
passed = true
pass('flushSync called')
@ -75,7 +75,7 @@ test('swallows the non-ready error', async ({ doesNotThrow }) => {
test('listener function triggers handler function parameter', async ({ pass, fail }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: false })
var passed = false
let passed = false
pino.final(pino(dest), () => {
passed = true
pass('handler function triggered')
@ -84,64 +84,64 @@ test('listener function triggers handler function parameter', async ({ pass, fai
if (passed === false) fail('handler function not triggered')
})
test('passes any error to the handler', async ({ is }) => {
test('passes any error to the handler', async ({ equal }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: false })
pino.final(pino(dest), (err) => {
is(err.message, 'test')
equal(err.message, 'test')
})(Error('test'))
})
test('passes a specialized final logger instance', async ({ is, isNot, error }) => {
test('passes a specialized final logger instance', async ({ equal, not, error }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: false })
const logger = pino(dest)
pino.final(logger, (err, finalLogger) => {
error(err)
is(typeof finalLogger.trace, 'function')
is(typeof finalLogger.debug, 'function')
is(typeof finalLogger.info, 'function')
is(typeof finalLogger.warn, 'function')
is(typeof finalLogger.error, 'function')
is(typeof finalLogger.fatal, 'function')
equal(typeof finalLogger.trace, 'function')
equal(typeof finalLogger.debug, 'function')
equal(typeof finalLogger.info, 'function')
equal(typeof finalLogger.warn, 'function')
equal(typeof finalLogger.error, 'function')
equal(typeof finalLogger.fatal, 'function')
isNot(finalLogger.trace, logger.trace)
isNot(finalLogger.debug, logger.debug)
isNot(finalLogger.info, logger.info)
isNot(finalLogger.warn, logger.warn)
isNot(finalLogger.error, logger.error)
isNot(finalLogger.fatal, logger.fatal)
not(finalLogger.trace, logger.trace)
not(finalLogger.debug, logger.debug)
not(finalLogger.info, logger.info)
not(finalLogger.warn, logger.warn)
not(finalLogger.error, logger.error)
not(finalLogger.fatal, logger.fatal)
is(finalLogger.child, logger.child)
is(finalLogger.levels, logger.levels)
equal(finalLogger.child, logger.child)
equal(finalLogger.levels, logger.levels)
})()
})
test('returns a specialized final logger instance if no handler is passed', async ({ is, isNot }) => {
test('returns a specialized final logger instance if no handler is passed', async ({ equal, not }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: false })
const logger = pino(dest)
const finalLogger = pino.final(logger)
is(typeof finalLogger.trace, 'function')
is(typeof finalLogger.debug, 'function')
is(typeof finalLogger.info, 'function')
is(typeof finalLogger.warn, 'function')
is(typeof finalLogger.error, 'function')
is(typeof finalLogger.fatal, 'function')
equal(typeof finalLogger.trace, 'function')
equal(typeof finalLogger.debug, 'function')
equal(typeof finalLogger.info, 'function')
equal(typeof finalLogger.warn, 'function')
equal(typeof finalLogger.error, 'function')
equal(typeof finalLogger.fatal, 'function')
isNot(finalLogger.trace, logger.trace)
isNot(finalLogger.debug, logger.debug)
isNot(finalLogger.info, logger.info)
isNot(finalLogger.warn, logger.warn)
isNot(finalLogger.error, logger.error)
isNot(finalLogger.fatal, logger.fatal)
not(finalLogger.trace, logger.trace)
not(finalLogger.debug, logger.debug)
not(finalLogger.info, logger.info)
not(finalLogger.warn, logger.warn)
not(finalLogger.error, logger.error)
not(finalLogger.fatal, logger.fatal)
is(finalLogger.child, logger.child)
is(finalLogger.levels, logger.levels)
equal(finalLogger.child, logger.child)
equal(finalLogger.levels, logger.levels)
})
test('final logger instances synchronously flush after a log method call', async ({ pass, fail, error }) => {
const dest = pino.destination({ dest: getPathToNull(), sync: false })
const logger = pino(dest)
var passed = false
var count = 0
let passed = false
let count = 0
dest.flushSync = () => {
count++
if (count === 2) {
@ -164,8 +164,8 @@ test('also instruments custom log methods', async ({ pass, fail, error }) => {
foo: 35
}
}, dest)
var passed = false
var count = 0
let passed = false
let count = 0
dest.flushSync = () => {
count++
if (count === 2) {

View File

@ -7,6 +7,6 @@ require('os').hostname = function () { return 'abcdefghijklmnopqr' }
const pino = require('../../..')
const logger = pino(pino.destination({ sync: false }))
for (let i = 0; i < 1000; i++) {
for (var i = 0; i < 1000; i++) {
logger.info('hello world')
}

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../'))
var logger = pino()
const pino = require(require.resolve('./../../'))
const logger = pino()
logger.info('hello')
logger.info('world')
process.exit(0)

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../'))
var logger = pino({}, pino.destination(1))
const pino = require(require.resolve('./../../'))
const logger = pino({}, pino.destination(1))
logger.info('hello')
logger.info('world')
process.exit(0)

View File

@ -1,6 +1,6 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
log.info('h')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: true,
serializers: {
a (num) {

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true }).child({ foo: 123 })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true }).child({ foo: 123 })
log.info('before')
log.setBindings({ foo: 456, bar: 789 })
log.info('after')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true }).child({ a: 1 })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true }).child({ a: 1 })
log.info('h')
log.child({ b: 2 }).info('h3')
setTimeout(() => log.info('h2'), 200)

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
timestamp: () => ',"custom-time-label":"test"',
prettyPrint: true
})

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
timestamp: () => ',"time":"test"',
prettyPrint: true
})

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: {
translateTime: true
}

View File

@ -1,9 +1,9 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: { errorProps: 'code,errno' }
})
var err = Object.assign(new Error('kaboom'), { code: 'ENOENT', errno: 1 })
const err = Object.assign(new Error('kaboom'), { code: 'ENOENT', errno: 1 })
log.error(err)

View File

@ -1,7 +1,7 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
log.error(new Error('kaboom'))
log.error(new Error('kaboom'), 'with a message')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
process.once('beforeExit', pino.final(log, (_, logger) => {
logger.info('beforeExit')
}))

View File

@ -1,7 +1,7 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
log.info('h')
pino.final(log).info('after')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
log.info('h')
process.once('beforeExit', pino.final(log, (_, logger) => {
logger.info('beforeExit')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: true,
formatters: {
log (obj) {

View File

@ -1,6 +1,6 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: { levelFirst: true } })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: { levelFirst: true } })
log.info('h')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
timestamp: false,
prettyPrint: true
})

View File

@ -1,6 +1,6 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: true })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
log.info({ msg: 'hello' })

View File

@ -1,6 +1,6 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: { levelFirst: true }, prettifier: require('pino-pretty') })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: { levelFirst: true }, prettifier: require('pino-pretty') })
log.info('h')

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: true,
redact: ['foo.an']
})

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: true,
serializers: {
foo (obj) {

View File

@ -1,8 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({
const pino = require(require.resolve('./../../../'))
const log = pino({
prettyPrint: true,
prettifier: function () {
return function () {

View File

@ -1,7 +1,7 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../../'))
var log = pino({ prettyPrint: { suppressFlushSyncWarning: true } })
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: { suppressFlushSyncWarning: true } })
log.info('h')
log.fatal('h1')

View File

@ -7,5 +7,5 @@ process.stdout.write = function (chunk) {
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('../../'))()
const pino = require(require.resolve('../../'))()
pino.info('me')

View File

@ -1,6 +1,6 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../'))
var asyncLogger = pino(pino.destination({ sync: false })).child({ hello: 'world' })
const pino = require(require.resolve('./../../'))
const asyncLogger = pino(pino.destination({ sync: false })).child({ hello: 'world' })
pino.final(asyncLogger, (_, logger) => logger.info('h'))()

View File

@ -1,9 +1,9 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../'))
var dest = pino.destination({ dest: 1, minLength: 4096, sync: false })
var logger = pino({}, dest)
const pino = require(require.resolve('./../../'))
const dest = pino.destination({ dest: 1, minLength: 4096, sync: false })
const logger = pino({}, dest)
logger.info('hello')
logger.info('world')
process.exit(0)

View File

@ -1,9 +1,9 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../'))
var dest = pino.destination({ dest: 1, minLength: 4096, sync: false })
var logger = pino({}, dest)
const pino = require(require.resolve('./../../'))
const dest = pino.destination({ dest: 1, minLength: 4096, sync: false })
const logger = pino({}, dest)
logger.info('hello')
logger.info('world')
dest.flushSync()

View File

@ -1,6 +1,6 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('os').hostname = function () { return 'abcdefghijklmnopqr' }
var pino = require(require.resolve('./../../'))
var asyncLogger = pino(pino.destination({ minLength: 4096, sync: false }))
const pino = require(require.resolve('./../../'))
const asyncLogger = pino(pino.destination({ minLength: 4096, sync: false }))
pino.final(asyncLogger, (_, logger) => logger.info('h'))()

View File

@ -76,12 +76,12 @@ test('no bindings formatter', async ({ match, notOk }) => {
match(log, { msg: 'hello world' })
})
test('log formatter', async ({ match, is }) => {
test('log formatter', async ({ match, equal }) => {
const stream = sink()
const logger = pino({
formatters: {
log (obj) {
is(obj.hasOwnProperty('msg'), false)
equal(obj.hasOwnProperty('msg'), false)
return { hello: 'world', ...obj }
}
}

View File

@ -6,18 +6,20 @@ const pino = require('../')
tap.test('log method hook', t => {
t.test('gets invoked', async t => {
t.plan(6)
t.plan(8)
const stream = sink()
const logger = pino({
hooks: {
logMethod (args, method) {
logMethod (args, method, level) {
t.type(args, Array)
t.is(args.length, 3)
t.deepEqual(args, ['a', 'b', 'c'])
t.type(level, 'number')
t.equal(args.length, 3)
t.equal(level, this.levels.values.info)
t.same(args, ['a', 'b', 'c'])
t.type(method, Function)
t.is(method.name, 'LOG')
t.equal(method.name, 'LOG')
method.apply(this, [args.join('-')])
}
@ -71,5 +73,25 @@ tap.test('log method hook', t => {
t.match(await o, { msg: 'c-d' })
})
t.test('get log level', async t => {
t.plan(3)
const stream = sink()
const logger = pino({
hooks: {
logMethod (args, method, level) {
t.type(level, 'number')
t.equal(level, this.levels.values.error)
method.apply(this, [args.join('-')])
}
}
}, stream)
const o = once(stream, 'data')
logger.error('a')
t.match(await o, { msg: 'a' })
})
t.end()
})

View File

@ -3,7 +3,7 @@
const http = require('http')
const os = require('os')
const semver = require('semver')
const { test } = require('tap')
const { test, skip } = require('tap')
const { sink, once } = require('./helper')
const pino = require('../')
@ -11,7 +11,7 @@ const { pid } = process
const hostname = os.hostname()
test('http request support', async ({ ok, same, error, teardown }) => {
var originalReq
let originalReq
const instance = pino(sink((chunk, enc) => {
ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
@ -24,8 +24,8 @@ test('http request support', async ({ ok, same, error, teardown }) => {
method: originalReq.method,
url: originalReq.url,
headers: originalReq.headers,
remoteAddress: originalReq.connection.remoteAddress,
remotePort: originalReq.connection.remotePort
remoteAddress: originalReq.socket.remoteAddress,
remotePort: originalReq.socket.remotePort
}
})
}))
@ -45,7 +45,7 @@ test('http request support', async ({ ok, same, error, teardown }) => {
})
test('http request support via serializer', async ({ ok, same, error, teardown }) => {
var originalReq
let originalReq
const instance = pino({
serializers: {
req: pino.stdSerializers.req
@ -62,8 +62,8 @@ test('http request support via serializer', async ({ ok, same, error, teardown }
method: originalReq.method,
url: originalReq.url,
headers: originalReq.headers,
remoteAddress: originalReq.connection.remoteAddress,
remotePort: originalReq.connection.remotePort
remoteAddress: originalReq.socket.remoteAddress,
remotePort: originalReq.socket.remotePort
}
})
}))
@ -83,8 +83,9 @@ test('http request support via serializer', async ({ ok, same, error, teardown }
server.close()
})
test('http request support via serializer without request connection', async ({ ok, same, error, teardown }) => {
var originalReq
// skipped because request connection is deprecated since v13, and request socket is always available
skip('http request support via serializer without request connection', async ({ ok, same, error, teardown }) => {
let originalReq
const instance = pino({
serializers: {
req: pino.stdSerializers.req
@ -104,8 +105,8 @@ test('http request support via serializer without request connection', async ({
}
}
if (semver.gte(process.version, '13.0.0')) {
expected.req.remoteAddress = originalReq.connection.remoteAddress
expected.req.remotePort = originalReq.connection.remotePort
expected.req.remoteAddress = originalReq.socket.remoteAddress
expected.req.remotePort = originalReq.socket.remotePort
}
same(chunk, expected)
}))
@ -127,7 +128,7 @@ test('http request support via serializer without request connection', async ({
})
test('http response support', async ({ ok, same, error, teardown }) => {
var originalRes
let originalRes
const instance = pino(sink((chunk, enc) => {
ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
@ -200,7 +201,7 @@ test('http response support via a serializer', async ({ ok, same, error, teardow
})
test('http request support via serializer in a child', async ({ ok, same, error, teardown }) => {
var originalReq
let originalReq
const instance = pino({
serializers: {
req: pino.stdSerializers.req
@ -217,8 +218,8 @@ test('http request support via serializer in a child', async ({ ok, same, error,
method: originalReq.method,
url: originalReq.url,
headers: originalReq.headers,
remoteAddress: originalReq.connection.remoteAddress,
remotePort: originalReq.connection.remotePort
remoteAddress: originalReq.socket.remoteAddress,
remotePort: originalReq.socket.remotePort
}
})
}))

View File

@ -3,41 +3,41 @@
const { test } = require('tap')
const pino = require('../')
test('can check if current level enabled', async ({ is }) => {
test('can check if current level enabled', async ({ equal }) => {
const log = pino({ level: 'debug' })
is(true, log.isLevelEnabled('debug'))
equal(true, log.isLevelEnabled('debug'))
})
test('can check if level enabled after level set', async ({ is }) => {
test('can check if level enabled after level set', async ({ equal }) => {
const log = pino()
is(false, log.isLevelEnabled('debug'))
equal(false, log.isLevelEnabled('debug'))
log.level = 'debug'
is(true, log.isLevelEnabled('debug'))
equal(true, log.isLevelEnabled('debug'))
})
test('can check if higher level enabled', async ({ is }) => {
test('can check if higher level enabled', async ({ equal }) => {
const log = pino({ level: 'debug' })
is(true, log.isLevelEnabled('error'))
equal(true, log.isLevelEnabled('error'))
})
test('can check if lower level is disabled', async ({ is }) => {
test('can check if lower level is disabled', async ({ equal }) => {
const log = pino({ level: 'error' })
is(false, log.isLevelEnabled('trace'))
equal(false, log.isLevelEnabled('trace'))
})
test('can check if child has current level enabled', async ({ is }) => {
test('can check if child has current level enabled', async ({ equal }) => {
const log = pino().child({ level: 'debug' })
is(true, log.isLevelEnabled('debug'))
is(true, log.isLevelEnabled('error'))
is(false, log.isLevelEnabled('trace'))
equal(true, log.isLevelEnabled('debug'))
equal(true, log.isLevelEnabled('error'))
equal(false, log.isLevelEnabled('trace'))
})
test('can check if custom level is enabled', async ({ is }) => {
test('can check if custom level is enabled', async ({ equal }) => {
const log = pino({
customLevels: { foo: 35 },
level: 'debug'
})
is(true, log.isLevelEnabled('foo'))
is(true, log.isLevelEnabled('error'))
is(false, log.isLevelEnabled('trace'))
equal(true, log.isLevelEnabled('foo'))
equal(true, log.isLevelEnabled('error'))
equal(false, log.isLevelEnabled('trace'))
})

View File

@ -10,7 +10,7 @@ const levelsLib = require('../lib/levels')
process.removeAllListeners('warning')
process.on('warning', () => {})
test('set the level by string', async ({ is }) => {
test('set the level by string', async ({ equal }) => {
const expected = [{
level: 50,
msg: 'this is an error'
@ -26,7 +26,7 @@ test('set the level by string', async ({ is }) => {
instance.fatal('this is fatal')
const result = await once(stream, 'data')
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
})
test('the wrong level throws', async ({ throws }) => {
@ -36,7 +36,7 @@ test('the wrong level throws', async ({ throws }) => {
})
})
test('set the level by number', async ({ is }) => {
test('set the level by number', async ({ equal }) => {
const expected = [{
level: 50,
msg: 'this is an error'
@ -53,29 +53,29 @@ test('set the level by number', async ({ is }) => {
instance.fatal('this is fatal')
const result = await once(stream, 'data')
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
})
test('exposes level string mappings', async ({ is }) => {
is(pino.levels.values.error, 50)
test('exposes level string mappings', async ({ equal }) => {
equal(pino.levels.values.error, 50)
})
test('exposes level number mappings', async ({ is }) => {
is(pino.levels.labels[50], 'error')
test('exposes level number mappings', async ({ equal }) => {
equal(pino.levels.labels[50], 'error')
})
test('returns level integer', async ({ is }) => {
test('returns level integer', async ({ equal }) => {
const instance = pino({ level: 'error' })
is(instance.levelVal, 50)
equal(instance.levelVal, 50)
})
test('child returns level integer', async ({ is }) => {
test('child returns level integer', async ({ equal }) => {
const parent = pino({ level: 'error' })
const child = parent.child({ foo: 'bar' })
is(child.levelVal, 50)
equal(child.levelVal, 50)
})
test('set the level via exported pino function', async ({ is }) => {
test('set the level via exported pino function', async ({ equal }) => {
const expected = [{
level: 50,
msg: 'this is an error'
@ -91,23 +91,23 @@ test('set the level via exported pino function', async ({ is }) => {
instance.fatal('this is fatal')
const result = await once(stream, 'data')
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
})
test('level-change event', async ({ is }) => {
test('level-change event', async ({ equal }) => {
const instance = pino()
function handle (lvl, val, prevLvl, prevVal) {
is(lvl, 'trace')
is(val, 10)
is(prevLvl, 'info')
is(prevVal, 30)
equal(lvl, 'trace')
equal(val, 10)
equal(prevLvl, 'info')
equal(prevVal, 30)
}
instance.on('level-change', handle)
instance.level = 'trace'
instance.removeListener('level-change', handle)
instance.level = 'info'
var count = 0
let count = 0
const l1 = () => count++
const l2 = () => count++
@ -124,7 +124,7 @@ test('level-change event', async ({ is }) => {
instance.removeListener('level-change', l2)
instance.level = 'info'
is(count, 6)
equal(count, 6)
})
test('enable', async ({ fail }) => {
@ -186,7 +186,7 @@ test('exposed labels', async ({ same }) => {
])
})
test('setting level in child', async ({ is }) => {
test('setting level in child', async ({ equal }) => {
const expected = [{
level: 50,
msg: 'this is an error'
@ -196,7 +196,7 @@ test('setting level in child', async ({ is }) => {
}]
const instance = pino(sink((result, enc, cb) => {
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
cb()
})).child({ level: 30 })
@ -206,13 +206,13 @@ test('setting level in child', async ({ is }) => {
instance.fatal('this is fatal')
})
test('setting level by assigning a number to level', async ({ is }) => {
test('setting level by assigning a number to level', async ({ equal }) => {
const instance = pino()
is(instance.levelVal, 30)
is(instance.level, 'info')
equal(instance.levelVal, 30)
equal(instance.level, 'info')
instance.level = 50
is(instance.levelVal, 50)
is(instance.level, 'error')
equal(instance.levelVal, 50)
equal(instance.level, 'error')
})
test('setting level by number to unknown value results in a throw', async ({ throws }) => {
@ -220,13 +220,13 @@ test('setting level by number to unknown value results in a throw', async ({ thr
throws(() => { instance.level = 973 })
})
test('setting level by assigning a known label to level', async ({ is }) => {
test('setting level by assigning a known label to level', async ({ equal }) => {
const instance = pino()
is(instance.levelVal, 30)
is(instance.level, 'info')
equal(instance.levelVal, 30)
equal(instance.level, 'info')
instance.level = 'error'
is(instance.levelVal, 50)
is(instance.level, 'error')
equal(instance.levelVal, 50)
equal(instance.level, 'error')
})
test('levelVal is read only', async ({ throws }) => {
@ -234,7 +234,7 @@ test('levelVal is read only', async ({ throws }) => {
throws(() => { instance.levelVal = 20 })
})
test('produces labels when told to', async ({ is }) => {
test('produces labels when told to', async ({ equal }) => {
const expected = [{
level: 'info',
msg: 'hello world'
@ -247,14 +247,14 @@ test('produces labels when told to', async ({ is }) => {
}
}, sink((result, enc, cb) => {
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
cb()
}))
instance.info('hello world')
})
test('resets levels from labels to numbers', async ({ is }) => {
test('resets levels from labels to numbers', async ({ equal }) => {
const expected = [{
level: 30,
msg: 'hello world'
@ -262,23 +262,23 @@ test('resets levels from labels to numbers', async ({ is }) => {
pino({ useLevelLabels: true })
const instance = pino({ useLevelLabels: false }, sink((result, enc, cb) => {
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
cb()
}))
instance.info('hello world')
})
test('aliases changeLevelName to levelKey', async ({ is }) => {
test('aliases changeLevelName to levelKey', async ({ equal }) => {
const instance = pino({ changeLevelName: 'priority' }, sink((result, enc, cb) => {
is(result.priority, 30)
equal(result.priority, 30)
cb()
}))
instance.info('hello world')
})
test('changes label naming when told to', async ({ is }) => {
test('changes label naming when told to', async ({ equal }) => {
const expected = [{
priority: 30,
msg: 'hello world'
@ -291,15 +291,15 @@ test('changes label naming when told to', async ({ is }) => {
}
}, sink((result, enc, cb) => {
const current = expected.shift()
is(result.priority, current.priority)
is(result.msg, current.msg)
equal(result.priority, current.priority)
equal(result.msg, current.msg)
cb()
}))
instance.info('hello world')
})
test('children produce labels when told to', async ({ is }) => {
test('children produce labels when told to', async ({ equal }) => {
const expected = [
{
level: 'info',
@ -318,7 +318,7 @@ test('children produce labels when told to', async ({ is }) => {
}
}, sink((result, enc, cb) => {
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
cb()
}))
@ -329,7 +329,7 @@ test('children produce labels when told to', async ({ is }) => {
child2.info('child 2')
})
test('produces labels for custom levels', async ({ is }) => {
test('produces labels for custom levels', async ({ equal }) => {
const expected = [
{
level: 'info',
@ -352,7 +352,7 @@ test('produces labels for custom levels', async ({ is }) => {
}
const instance = pino(opts, sink((result, enc, cb) => {
const current = expected.shift()
check(is, result, current.level, current.msg)
check(equal, result, current.level, current.msg)
cb()
}))
@ -360,7 +360,7 @@ test('produces labels for custom levels', async ({ is }) => {
instance.foo('foobar')
})
test('setting levelKey does not affect labels when told to', async ({ is }) => {
test('setting levelKey does not affect labels when told to', async ({ equal }) => {
const instance = pino(
{
formatters: {
@ -370,7 +370,7 @@ test('setting levelKey does not affect labels when told to', async ({ is }) => {
}
},
sink((result, enc, cb) => {
is(result.priority, 'info')
equal(result.priority, 'info')
cb()
})
)
@ -378,7 +378,7 @@ test('setting levelKey does not affect labels when told to', async ({ is }) => {
instance.info('hello world')
})
test('throws when creating a default label that does not exist in logger levels', async ({ is, throws }) => {
test('throws when creating a default label that does not exist in logger levels', async ({ equal, throws }) => {
const defaultLevel = 'foo'
throws(() => {
pino({
@ -393,11 +393,11 @@ test('throws when creating a default label that does not exist in logger levels'
level: defaultLevel
})
} catch ({ message }) {
is(message, `default level:${defaultLevel} must be included in custom levels`)
equal(message, `default level:${defaultLevel} must be included in custom levels`)
}
})
test('throws when creating a default value that does not exist in logger levels', async ({ is, throws }) => {
test('throws when creating a default value that does not exist in logger levels', async ({ equal, throws }) => {
const defaultLevel = 15
throws(() => {
pino({
@ -412,11 +412,11 @@ test('throws when creating a default value that does not exist in logger levels'
level: defaultLevel
})
} catch ({ message }) {
is(message, `default level:${defaultLevel} must be included in custom levels`)
equal(message, `default level:${defaultLevel} must be included in custom levels`)
}
})
test('throws when creating a default value that does not exist in logger levels', async ({ is, throws }) => {
test('throws when creating a default value that does not exist in logger levels', async ({ equal, throws }) => {
throws(() => {
pino({
customLevels: {
@ -433,17 +433,17 @@ test('throws when creating a default value that does not exist in logger levels'
useOnlyCustomLevels: true
})
} catch ({ message }) {
is(message, 'default level:info must be included in custom levels')
equal(message, 'default level:info must be included in custom levels')
}
})
test('passes when creating a default value that exists in logger levels', async ({ is, throws }) => {
test('passes when creating a default value that exists in logger levels', async ({ equal, throws }) => {
pino({
level: 30
})
})
test('log null value when message is null', async ({ is }) => {
test('log null value when message is null', async ({ equal }) => {
const expected = {
msg: null,
level: 30
@ -455,10 +455,10 @@ test('log null value when message is null', async ({ is }) => {
instance.info(null)
const result = await once(stream, 'data')
check(is, result, expected.level, expected.msg)
check(equal, result, expected.level, expected.msg)
})
test('formats when base param is null', async ({ is }) => {
test('formats when base param is null', async ({ equal }) => {
const expected = {
msg: 'a string',
level: 30
@ -470,7 +470,7 @@ test('formats when base param is null', async ({ is }) => {
instance.info(null, 'a %s', 'string')
const result = await once(stream, 'data')
check(is, result, expected.level, expected.msg)
check(equal, result, expected.level, expected.msg)
})
test('fatal method sync-flushes the destination if sync flushing is available', async ({ pass, doesNotThrow, plan }) => {
@ -515,7 +515,7 @@ test('calling silent method on child logger', async ({ fail }) => {
child.silent('hello world')
})
test('changing level from info to silent and back to info', async ({ is }) => {
test('changing level from info to silent and back to info', async ({ equal }) => {
const expected = {
level: 30,
msg: 'hello world'
@ -526,15 +526,15 @@ test('changing level from info to silent and back to info', async ({ is }) => {
instance.level = 'silent'
instance.info('hello world')
let result = stream.read()
is(result, null)
equal(result, null)
instance.level = 'info'
instance.info('hello world')
result = await once(stream, 'data')
check(is, result, expected.level, expected.msg)
check(equal, result, expected.level, expected.msg)
})
test('changing level from info to silent and back to info in child logger', async ({ is }) => {
test('changing level from info to silent and back to info in child logger', async ({ equal }) => {
const expected = {
level: 30,
msg: 'hello world'
@ -545,17 +545,17 @@ test('changing level from info to silent and back to info in child logger', asyn
child.level = 'silent'
child.info('hello world')
let result = stream.read()
is(result, null)
equal(result, null)
child.level = 'info'
child.info('hello world')
result = await once(stream, 'data')
check(is, result, expected.level, expected.msg)
check(equal, result, expected.level, expected.msg)
})
// testing for potential loss of Pino constructor scope from serializers - an edge case with circular refs see: https://github.com/pinojs/pino/issues/833
test('trying to get levels when `this` is no longer a Pino instance returns an empty string', async ({ is }) => {
test('trying to get levels when `this` is no longer a Pino instance returns an empty string', async ({ equal }) => {
const notPinoInstance = { some: 'object', getLevel: levelsLib.getLevel }
const blankedLevelValue = notPinoInstance.getLevel()
is(blankedLevelValue, '')
equal(blankedLevelValue, '')
})

View File

@ -7,14 +7,14 @@ const pino = require('../')
const { pid } = process
const hostname = os.hostname()
test('metadata works', async ({ ok, same, is }) => {
test('metadata works', async ({ ok, same, equal }) => {
const now = Date.now()
const instance = pino({}, {
[Symbol.for('pino.metadata')]: true,
write (chunk) {
is(instance, this.lastLogger)
is(30, this.lastLevel)
is('a msg', this.lastMsg)
equal(instance, this.lastLogger)
equal(30, this.lastLevel)
equal('a msg', this.lastMsg)
ok(Number(this.lastTime) >= now)
same(this.lastObj, { hello: 'world', msg: 'a msg' })
const result = JSON.parse(chunk)
@ -33,13 +33,13 @@ test('metadata works', async ({ ok, same, is }) => {
instance.info({ hello: 'world' }, 'a msg')
})
test('child loggers works', async ({ ok, same, is }) => {
test('child loggers works', async ({ ok, same, equal }) => {
const instance = pino({}, {
[Symbol.for('pino.metadata')]: true,
write (chunk) {
is(child, this.lastLogger)
is(30, this.lastLevel)
is('a msg', this.lastMsg)
equal(child, this.lastLogger)
equal(30, this.lastLevel)
equal('a msg', this.lastMsg)
same(this.lastObj, { from: 'child', msg: 'a msg' })
const result = JSON.parse(chunk)
ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
@ -59,13 +59,13 @@ test('child loggers works', async ({ ok, same, is }) => {
child.info({ from: 'child' }, 'a msg')
})
test('without object', async ({ ok, same, is }) => {
test('without object', async ({ ok, same, equal }) => {
const instance = pino({}, {
[Symbol.for('pino.metadata')]: true,
write (chunk) {
is(instance, this.lastLogger)
is(30, this.lastLevel)
is('a msg', this.lastMsg)
equal(instance, this.lastLogger)
equal(30, this.lastLevel)
equal('a msg', this.lastMsg)
same({ msg: 'a msg' }, this.lastObj)
const result = JSON.parse(chunk)
ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
@ -82,13 +82,13 @@ test('without object', async ({ ok, same, is }) => {
instance.info('a msg')
})
test('without msg', async ({ ok, same, is }) => {
test('without msg', async ({ ok, same, equal }) => {
const instance = pino({}, {
[Symbol.for('pino.metadata')]: true,
write (chunk) {
is(instance, this.lastLogger)
is(30, this.lastLevel)
is(undefined, this.lastMsg)
equal(instance, this.lastLogger)
equal(30, this.lastLevel)
equal(undefined, this.lastMsg)
same({ hello: 'world' }, this.lastObj)
const result = JSON.parse(chunk)
ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')

View File

@ -9,8 +9,8 @@ const { once } = require('./helper')
const pino = require('../')
const strip = require('strip-ansi')
test('can be enabled via exported pino function', async ({ isNot }) => {
var actual = ''
test('can be enabled via exported pino function', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'basic.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -18,11 +18,11 @@ test('can be enabled via exported pino function', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
})
test('can be enabled via exported pino function with pretty configuration', async ({ isNot }) => {
var actual = ''
test('can be enabled via exported pino function with pretty configuration', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'level-first.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -30,11 +30,11 @@ test('can be enabled via exported pino function with pretty configuration', asyn
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/^INFO.*h/), null)
not(strip(actual).match(/^INFO.*h/), null)
})
test('can be enabled via exported pino function with prettifier', async ({ isNot }) => {
var actual = ''
test('can be enabled via exported pino function with prettifier', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'pretty-factory.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -43,14 +43,14 @@ test('can be enabled via exported pino function with prettifier', async ({ isNot
}))
await once(child, 'close')
isNot(strip(actual).match(/^INFO.*h/), null)
not(strip(actual).match(/^INFO.*h/), null)
})
test('does not throw error when enabled with stream specified', async ({ doesNotThrow }) => {
doesNotThrow(() => pino({ prettyPrint: true }, process.stdout))
})
test('throws when prettyPrint is true but pino-pretty module is not installed', async ({ throws, is }) => {
test('throws when prettyPrint is true but pino-pretty module is not installed', async ({ throws, equal }) => {
// pino pretty *is* installed, and probably also cached, so rather than
// messing with the filesystem the simplest way to generate a not found
// error is to simulate it:
@ -60,17 +60,17 @@ test('throws when prettyPrint is true but pino-pretty module is not installed',
}
throws(() => pino({ prettyPrint: true }))
try { pino({ prettyPrint: true }) } catch ({ message }) {
is(message, 'Missing `pino-pretty` module: `pino-pretty` must be installed separately')
equal(message, 'Missing `pino-pretty` module: `pino-pretty` must be installed separately')
}
require.cache[require.resolve('pino-pretty')].exports = prettyFactory
})
test('can send pretty print to custom stream', async ({ is }) => {
test('can send pretty print to custom stream', async ({ equal }) => {
const dest = new Writable({
objectMode: true,
write (formatted, enc) {
is(/^INFO.*foo\n$/.test(formatted), true)
equal(/^INFO.*foo\n$/.test(formatted), true)
}
})
@ -84,8 +84,8 @@ test('can send pretty print to custom stream', async ({ is }) => {
log.info('foo')
})
test('ignores `undefined` from prettifier', async ({ is }) => {
var actual = ''
test('ignores `undefined` from prettifier', async ({ equal }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'skipped-output.js')])
child.stdout.pipe(writer((s, enc) => {
@ -93,11 +93,11 @@ test('ignores `undefined` from prettifier', async ({ is }) => {
}))
await once(child, 'close')
is(actual, '')
equal(actual, '')
})
test('parses and outputs chindings', async ({ is, isNot }) => {
var actual = ''
test('parses and outputs chindings', async ({ equal, not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'child.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -105,15 +105,15 @@ test('parses and outputs chindings', async ({ is, isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h2/), null)
isNot(strip(actual).match(/a: 1/), null)
isNot(strip(actual).match(/b: 2/), null)
is(strip(actual).match(/a: 1/g).length, 3)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h2/), null)
not(strip(actual).match(/a: 1/), null)
not(strip(actual).match(/b: 2/), null)
equal(strip(actual).match(/a: 1/g).length, 3)
})
test('applies updated chindings', async ({ is, isNot }) => {
var actual = ''
test('applies updated chindings', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'child-with-updated-chindings.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -121,13 +121,13 @@ test('applies updated chindings', async ({ is, isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/foo: 123/), null)
isNot(strip(actual).match(/foo: 456/), null)
isNot(strip(actual).match(/bar: 789/), null)
not(strip(actual).match(/foo: 123/), null)
not(strip(actual).match(/foo: 456/), null)
not(strip(actual).match(/bar: 789/), null)
})
test('applies formatters', async ({ is, isNot }) => {
var actual = ''
test('applies formatters', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'formatters.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -135,12 +135,12 @@ test('applies formatters', async ({ is, isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
isNot(strip(actual).match(/foo: "formatted_bar"/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/foo: "formatted_bar"/), null)
})
test('parses and outputs chindings with serializer', async ({ is, isNot }) => {
var actual = ''
test('parses and outputs chindings with serializer', async ({ equal, not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'child-with-serializer.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -148,18 +148,18 @@ test('parses and outputs chindings with serializer', async ({ is, isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h2/), null)
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h3/), null)
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h4/), null)
isNot(strip(actual).match(/a: 2/), null)
isNot(strip(actual).match(/a: 16/), null)
isNot(strip(actual).match(/a: 42/), null)
is(strip(actual).match(/a: /g).length, 4)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h2/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h3/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h4/), null)
not(strip(actual).match(/a: 2/), null)
not(strip(actual).match(/a: 16/), null)
not(strip(actual).match(/a: 42/), null)
equal(strip(actual).match(/a: /g).length, 4)
})
test('applies serializers', async ({ is, isNot }) => {
var actual = ''
test('applies serializers', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'serializers.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -167,12 +167,12 @@ test('applies serializers', async ({ is, isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
isNot(strip(actual).match(/foo: "bar"/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/foo: "bar"/), null)
})
test('applies redaction rules', async ({ is, isNot }) => {
var actual = ''
test('applies redaction rules', async ({ equal, not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'redact.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -180,13 +180,13 @@ test('applies redaction rules', async ({ is, isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
isNot(strip(actual).match(/\[Redacted\]/), null)
is(strip(actual).match(/object/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/\[Redacted\]/), null)
equal(strip(actual).match(/object/), null)
})
test('dateformat', async ({ isNot }) => {
var actual = ''
test('dateformat', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'dateformat.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -194,11 +194,11 @@ test('dateformat', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): h/), null)
})
test('without timestamp', async ({ isNot }) => {
var actual = ''
test('without timestamp', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'no-time.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -206,11 +206,11 @@ test('without timestamp', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).slice(2), '[]')
not(strip(actual).slice(2), '[]')
})
test('with custom timestamp', async ({ is }) => {
var actual = ''
test('with custom timestamp', async ({ equal }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'custom-time.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -218,11 +218,11 @@ test('with custom timestamp', async ({ is }) => {
cb()
}))
await once(child, 'close')
is(strip(actual).slice(0, 6), '[test]')
equal(strip(actual).slice(0, 6), '[test]')
})
test('with custom timestamp label', async ({ is }) => {
var actual = ''
test('with custom timestamp label', async ({ equal }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'custom-time-label.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -230,11 +230,11 @@ test('with custom timestamp label', async ({ is }) => {
cb()
}))
await once(child, 'close')
is(strip(actual).slice(0, 6), '[test]')
equal(strip(actual).slice(0, 6), '[test]')
})
test('errors', async ({ isNot }) => {
var actual = ''
test('errors', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'error.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -242,13 +242,13 @@ test('errors', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): kaboom/), null)
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): with a message/), null)
isNot(strip(actual).match(/.*error\.js.*/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): kaboom/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): with a message/), null)
not(strip(actual).match(/.*error\.js.*/), null)
})
test('errors with props', async ({ isNot }) => {
var actual = ''
test('errors with props', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'error-props.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -256,14 +256,14 @@ test('errors with props', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): kaboom/), null)
isNot(strip(actual).match(/"code": "ENOENT"/), null)
isNot(strip(actual).match(/"errno": 1/), null)
isNot(strip(actual).match(/.*error-props\.js.*/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): kaboom/), null)
not(strip(actual).match(/"code": "ENOENT"/), null)
not(strip(actual).match(/"errno": 1/), null)
not(strip(actual).match(/.*error-props\.js.*/), null)
})
test('final works with pretty', async ({ isNot }) => {
var actual = ''
test('final works with pretty', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'final.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -271,12 +271,12 @@ test('final works with pretty', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/WARN\s+\(123456 on abcdefghijklmnopqr\): pino.final with prettyPrint does not support flushing/), null)
isNot(strip(actual).match(/INFO\s+\(123456 on abcdefghijklmnopqr\): beforeExit/), null)
not(strip(actual).match(/WARN\s+\(123456 on abcdefghijklmnopqr\): pino.final with prettyPrint does not support flushing/), null)
not(strip(actual).match(/INFO\s+\(123456 on abcdefghijklmnopqr\): beforeExit/), null)
})
test('final works when returning a logger', async ({ isNot }) => {
var actual = ''
test('final works when returning a logger', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'final-return.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -284,12 +284,12 @@ test('final works when returning a logger', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/WARN\s+\(123456 on abcdefghijklmnopqr\): pino.final with prettyPrint does not support flushing/), null)
isNot(strip(actual).match(/INFO\s+\(123456 on abcdefghijklmnopqr\): after/), null)
not(strip(actual).match(/WARN\s+\(123456 on abcdefghijklmnopqr\): pino.final with prettyPrint does not support flushing/), null)
not(strip(actual).match(/INFO\s+\(123456 on abcdefghijklmnopqr\): after/), null)
})
test('final works without prior logging', async ({ isNot }) => {
var actual = ''
test('final works without prior logging', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'final-no-log-before.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -297,12 +297,12 @@ test('final works without prior logging', async ({ isNot }) => {
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/WARN\s+: pino.final with prettyPrint does not support flushing/), null)
isNot(strip(actual).match(/INFO\s+\(123456 on abcdefghijklmnopqr\): beforeExit/), null)
not(strip(actual).match(/WARN\s*: pino.final with prettyPrint does not support flushing/), null)
not(strip(actual).match(/INFO\s*\(123456 on abcdefghijklmnopqr\): beforeExit/), null)
})
test('suppress flush sync warning when corresponding option is specified', async ({ isNot, is }) => {
var actual = ''
test('suppress flush sync warning when corresponding option is specified', async ({ equal }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'suppress-flush-sync-warning.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -310,11 +310,11 @@ test('suppress flush sync warning when corresponding option is specified', async
cb()
}))
await once(child, 'close')
is(strip(actual).match(/WARN\s+\(123456 on abcdefghijklmnopqr\): pino.final with prettyPrint does not support flushing/), null)
equal(strip(actual).match(/WARN\s+\(123456 on abcdefghijklmnopqr\): pino.final with prettyPrint does not support flushing/), null)
})
test('works as expected with an object with the msg prop', async ({ isNot }) => {
var actual = ''
test('works as expected with an object with the msg prop', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], [join(__dirname, 'fixtures', 'pretty', 'obj-msg-prop.js')])
child.stdout.pipe(writer((s, enc, cb) => {
@ -322,18 +322,18 @@ test('works as expected with an object with the msg prop', async ({ isNot }) =>
cb()
}))
await once(child, 'close')
isNot(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): hello/), null)
not(strip(actual).match(/\(123456 on abcdefghijklmnopqr\): hello/), null)
})
test('should not lose stream metadata for streams with `needsMetadataGsym` flag', async ({ isNot }) => {
test('should not lose stream metadata for streams with `needsMetadataGsym` flag', async ({ not }) => {
const dest = new Writable({
objectMode: true,
write () {
isNot(typeof this.lastLevel === 'undefined', true)
isNot(typeof this.lastMsg === 'undefined', true)
isNot(typeof this.lastObj === 'undefined', true)
isNot(typeof this.lastTime === 'undefined', true)
isNot(typeof this.lastLogger === 'undefined', true)
not(typeof this.lastLevel === 'undefined', true)
not(typeof this.lastMsg === 'undefined', true)
not(typeof this.lastObj === 'undefined', true)
not(typeof this.lastTime === 'undefined', true)
not(typeof this.lastLogger === 'undefined', true)
}
})
@ -345,15 +345,15 @@ test('should not lose stream metadata for streams with `needsMetadataGsym` flag'
log.info('foo')
})
test('should not add stream metadata for streams without `needsMetadataGsym` flag', async ({ is }) => {
test('should not add stream metadata for streams without `needsMetadataGsym` flag', async ({ equal }) => {
const dest = new Writable({
objectMode: true,
write () {
is(typeof this.lastLevel === 'undefined', true)
is(typeof this.lastMsg === 'undefined', true)
is(typeof this.lastObj === 'undefined', true)
is(typeof this.lastTime === 'undefined', true)
is(typeof this.lastLogger === 'undefined', true)
equal(typeof this.lastLevel === 'undefined', true)
equal(typeof this.lastMsg === 'undefined', true)
equal(typeof this.lastObj === 'undefined', true)
equal(typeof this.lastTime === 'undefined', true)
equal(typeof this.lastLogger === 'undefined', true)
}
})

View File

@ -40,37 +40,37 @@ test('redact.paths option throws if array contains an invalid path', async (
})
})
test('redact option top level key', async ({ is }) => {
test('redact option top level key', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key'] }, stream)
instance.info({
key: { redact: 'me' }
})
const { key } = await once(stream, 'data')
is(key, '[Redacted]')
equal(key, '[Redacted]')
})
test('redact option top level key next level key', async ({ is }) => {
test('redact option top level key next level key', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key', 'key.foo'] }, stream)
instance.info({
key: { redact: 'me' }
})
const { key } = await once(stream, 'data')
is(key, '[Redacted]')
equal(key, '[Redacted]')
})
test('redact option next level key then top level key', async ({ is }) => {
test('redact option next level key then top level key', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key.foo', 'key'] }, stream)
instance.info({
key: { redact: 'me' }
})
const { key } = await once(stream, 'data')
is(key, '[Redacted]')
equal(key, '[Redacted]')
})
test('redact option object', async ({ is }) => {
test('redact option object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
instance.info({
@ -88,10 +88,10 @@ test('redact option object', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('redact option child object', async ({ is }) => {
test('redact option child object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
instance.child({
@ -109,10 +109,10 @@ test('redact option child object', async ({ is }) => {
}
}).info('message completed')
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('redact option interpolated object', async ({ is }) => {
test('redact option interpolated object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
@ -131,10 +131,10 @@ test('redact option interpolated object', async ({ is }) => {
}
})
const { msg } = await once(stream, 'data')
is(JSON.parse(msg.replace(/test /, '')).req.headers.cookie, '[Redacted]')
equal(JSON.parse(msg.replace(/test /, '')).req.headers.cookie, '[Redacted]')
})
test('redact.paths option object', async ({ is }) => {
test('redact.paths option object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
instance.info({
@ -152,10 +152,10 @@ test('redact.paths option object', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('redact.paths option child object', async ({ is }) => {
test('redact.paths option child object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
instance.child({
@ -173,10 +173,10 @@ test('redact.paths option child object', async ({ is }) => {
}
}).info('message completed')
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('redact.paths option interpolated object', async ({ is }) => {
test('redact.paths option interpolated object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
@ -195,10 +195,10 @@ test('redact.paths option interpolated object', async ({ is }) => {
}
})
const { msg } = await once(stream, 'data')
is(JSON.parse(msg.replace(/test /, '')).req.headers.cookie, '[Redacted]')
equal(JSON.parse(msg.replace(/test /, '')).req.headers.cookie, '[Redacted]')
})
test('redact.censor option sets the redact value', async ({ is }) => {
test('redact.censor option sets the redact value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], censor: 'test' } }, stream)
instance.info({
@ -216,20 +216,20 @@ test('redact.censor option sets the redact value', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, 'test')
equal(req.headers.cookie, 'test')
})
test('redact.censor option can be a function that accepts value and path arguments', async ({ is }) => {
test('redact.censor option can be a function that accepts value and path arguments', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['topLevel'], censor: (value, path) => value + ' ' + path.join('.') } }, stream)
instance.info({
topLevel: 'test'
})
const { topLevel } = await once(stream, 'data')
is(topLevel, 'test topLevel')
equal(topLevel, 'test topLevel')
})
test('redact.censor option can be a function that accepts value and path arguments (nested path)', async ({ is }) => {
test('redact.censor option can be a function that accepts value and path arguments (nested path)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], censor: (value, path) => value + ' ' + path.join('.') } }, stream)
instance.info({
@ -247,10 +247,10 @@ test('redact.censor option can be a function that accepts value and path arg
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1; req.headers.cookie')
equal(req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1; req.headers.cookie')
})
test('redact.remove option removes both key and value', async ({ is }) => {
test('redact.remove option removes both key and value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], remove: true } }, stream)
instance.info({
@ -268,49 +268,49 @@ test('redact.remove option removes both key and value', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is('cookie' in req.headers, false)
equal('cookie' in req.headers, false)
})
test('redact.remove top level key - object value', async ({ is }) => {
test('redact.remove top level key - object value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['key'], remove: true } }, stream)
instance.info({
key: { redact: 'me' }
})
const o = await once(stream, 'data')
is('key' in o, false)
equal('key' in o, false)
})
test('redact.remove top level key - number value', async ({ is }) => {
test('redact.remove top level key - number value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['key'], remove: true } }, stream)
instance.info({
key: 1
})
const o = await once(stream, 'data')
is('key' in o, false)
equal('key' in o, false)
})
test('redact.remove top level key - boolean value', async ({ is }) => {
test('redact.remove top level key - boolean value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['key'], remove: true } }, stream)
instance.info({
key: false
})
const o = await once(stream, 'data')
is('key' in o, false)
equal('key' in o, false)
})
test('redact.remove top level key in child logger', async ({ is }) => {
test('redact.remove top level key in child logger', async ({ equal }) => {
const stream = sink()
const opts = { redact: { paths: ['key'], remove: true } }
const instance = pino(opts, stream).child({ key: { redact: 'me' } })
instance.info('test')
const o = await once(stream, 'data')
is('key' in o, false)
equal('key' in o, false)
})
test('redact.paths preserves original object values after the log write', async ({ is }) => {
test('redact.paths preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
const obj = {
@ -329,11 +329,11 @@ test('redact.paths preserves original object values after the log write', async
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.req.headers.cookie, '[Redacted]')
is(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
equal(o.req.headers.cookie, '[Redacted]')
equal(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
})
test('redact.paths preserves original object values after the log write', async ({ is }) => {
test('redact.paths preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
const obj = {
@ -352,11 +352,11 @@ test('redact.paths preserves original object values after the log write', async
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.req.headers.cookie, '[Redacted]')
is(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
equal(o.req.headers.cookie, '[Redacted]')
equal(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
})
test('redact.censor preserves original object values after the log write', async ({ is }) => {
test('redact.censor preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], censor: 'test' } }, stream)
const obj = {
@ -375,11 +375,11 @@ test('redact.censor preserves original object values after the log write', async
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.req.headers.cookie, 'test')
is(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
equal(o.req.headers.cookie, 'test')
equal(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
})
test('redact.remove preserves original object values after the log write', async ({ is }) => {
test('redact.remove preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], remove: true } }, stream)
const obj = {
@ -398,11 +398,11 @@ test('redact.remove preserves original object values after the log write', async
}
instance.info(obj)
const o = await once(stream, 'data')
is('cookie' in o.req.headers, false)
is('cookie' in obj.req.headers, true)
equal('cookie' in o.req.headers, false)
equal('cookie' in obj.req.headers, true)
})
test('redact supports last position wildcard paths', async ({ is }) => {
test('redact supports last position wildcard paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.*'] }, stream)
instance.info({
@ -420,12 +420,12 @@ test('redact supports last position wildcard paths', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
is(req.headers.host, '[Redacted]')
is(req.headers.connection, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
equal(req.headers.host, '[Redacted]')
equal(req.headers.connection, '[Redacted]')
})
test('redact supports first position wildcard paths', async ({ is }) => {
test('redact supports first position wildcard paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*.headers'] }, stream)
instance.info({
@ -443,10 +443,10 @@ test('redact supports first position wildcard paths', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req.headers, '[Redacted]')
equal(req.headers, '[Redacted]')
})
test('redact supports first position wildcards before other paths', async ({ is }) => {
test('redact supports first position wildcards before other paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*.headers.cookie', 'req.id'] }, stream)
instance.info({
@ -464,11 +464,11 @@ test('redact supports first position wildcards before other paths', async ({
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
is(req.id, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
equal(req.id, '[Redacted]')
})
test('redact supports first position wildcards after other paths', async ({ is }) => {
test('redact supports first position wildcards after other paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.id', '*.headers.cookie'] }, stream)
instance.info({
@ -486,11 +486,11 @@ test('redact supports first position wildcards after other paths', async ({
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
is(req.id, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
equal(req.id, '[Redacted]')
})
test('redact supports first position wildcards after top level keys', async ({ is }) => {
test('redact supports first position wildcards after top level keys', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key', '*.headers.cookie'] }, stream)
instance.info({
@ -508,10 +508,10 @@ test('redact supports first position wildcards after top level keys', async
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('redact supports top level wildcard', async ({ is }) => {
test('redact supports top level wildcard', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*'] }, stream)
instance.info({
@ -529,10 +529,10 @@ test('redact supports top level wildcard', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req, '[Redacted]')
equal(req, '[Redacted]')
})
test('redact supports top level wildcard with a censor function', async ({ is }) => {
test('redact supports top level wildcard with a censor function', async ({ equal }) => {
const stream = sink()
const instance = pino({
redact: {
@ -555,10 +555,10 @@ test('redact supports top level wildcard with a censor function', async ({ i
}
})
const { req } = await once(stream, 'data')
is(req, '[Redacted]')
equal(req, '[Redacted]')
})
test('redact supports top level wildcard and leading wildcard', async ({ is }) => {
test('redact supports top level wildcard and leading wildcard', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*', '*.req'] }, stream)
instance.info({
@ -576,10 +576,10 @@ test('redact supports top level wildcard and leading wildcard', async ({ is
}
})
const { req } = await once(stream, 'data')
is(req, '[Redacted]')
equal(req, '[Redacted]')
})
test('redact supports intermediate wildcard paths', async ({ is }) => {
test('redact supports intermediate wildcard paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.*.cookie'] }, stream)
instance.info({
@ -597,10 +597,10 @@ test('redact supports intermediate wildcard paths', async ({ is }) => {
}
})
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('redacts numbers at the top level', async ({ is }) => {
test('redacts numbers at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['id'] }, stream)
const obj = {
@ -608,10 +608,10 @@ test('redacts numbers at the top level', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.id, '[Redacted]')
equal(o.id, '[Redacted]')
})
test('redacts booleans at the top level', async ({ is }) => {
test('redacts booleans at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['maybe'] }, stream)
const obj = {
@ -619,10 +619,10 @@ test('redacts booleans at the top level', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.maybe, '[Redacted]')
equal(o.maybe, '[Redacted]')
})
test('redacts strings at the top level', async ({ is }) => {
test('redacts strings at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['s'] }, stream)
const obj = {
@ -630,10 +630,10 @@ test('redacts strings at the top level', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.s, '[Redacted]')
equal(o.s, '[Redacted]')
})
test('does not redact primitives if not objects', async ({ is }) => {
test('does not redact primitives if not objects', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a.b'] }, stream)
const obj = {
@ -641,10 +641,10 @@ test('does not redact primitives if not objects', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.a, 42)
equal(o.a, 42)
})
test('redacts null at the top level', async ({ is }) => {
test('redacts null at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['n'] }, stream)
const obj = {
@ -652,10 +652,10 @@ test('redacts null at the top level', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.n, '[Redacted]')
equal(o.n, '[Redacted]')
})
test('supports bracket notation', async ({ is }) => {
test('supports bracket notation', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a["b.b"]'] }, stream)
const obj = {
@ -663,10 +663,10 @@ test('supports bracket notation', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.a['b.b'], '[Redacted]')
equal(o.a['b.b'], '[Redacted]')
})
test('supports bracket notation with further nesting', async ({ is }) => {
test('supports bracket notation with further nesting', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a["b.b"].c'] }, stream)
const obj = {
@ -674,10 +674,10 @@ test('supports bracket notation with further nesting', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.a['b.b'].c, '[Redacted]')
equal(o.a['b.b'].c, '[Redacted]')
})
test('supports bracket notation with empty string as path segment', async ({ is }) => {
test('supports bracket notation with empty string as path segment', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a[""].c'] }, stream)
const obj = {
@ -685,10 +685,10 @@ test('supports bracket notation with empty string as path segment', async ({ is
}
instance.info(obj)
const o = await once(stream, 'data')
is(o.a[''].c, '[Redacted]')
equal(o.a[''].c, '[Redacted]')
})
test('supports leading bracket notation (single quote)', async ({ is }) => {
test('supports leading bracket notation (single quote)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[\'a.a\'].b'] }, stream)
const obj = {
@ -696,10 +696,10 @@ test('supports leading bracket notation (single quote)', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o['a.a'].b, '[Redacted]')
equal(o['a.a'].b, '[Redacted]')
})
test('supports leading bracket notation (double quote)', async ({ is }) => {
test('supports leading bracket notation (double quote)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['["a.a"].b'] }, stream)
const obj = {
@ -707,10 +707,10 @@ test('supports leading bracket notation (double quote)', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o['a.a'].b, '[Redacted]')
equal(o['a.a'].b, '[Redacted]')
})
test('supports leading bracket notation (backtick quote)', async ({ is }) => {
test('supports leading bracket notation (backtick quote)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[`a.a`].b'] }, stream)
const obj = {
@ -718,10 +718,10 @@ test('supports leading bracket notation (backtick quote)', async ({ is }) => {
}
instance.info(obj)
const o = await once(stream, 'data')
is(o['a.a'].b, '[Redacted]')
equal(o['a.a'].b, '[Redacted]')
})
test('supports leading bracket notation (single-segment path)', async ({ is }) => {
test('supports leading bracket notation (single-segment path)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[`a.a`]'] }, stream)
const obj = {
@ -729,10 +729,10 @@ test('supports leading bracket notation (single-segment path)', async ({ is }) =
}
instance.info(obj)
const o = await once(stream, 'data')
is(o['a.a'], '[Redacted]')
equal(o['a.a'], '[Redacted]')
})
test('supports leading bracket notation (single-segment path, wilcard)', async ({ is }) => {
test('supports leading bracket notation (single-segment path, wilcard)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[*]'] }, stream)
const obj = {
@ -740,10 +740,10 @@ test('supports leading bracket notation (single-segment path, wilcard)', async (
}
instance.info(obj)
const o = await once(stream, 'data')
is(o['a.a'], '[Redacted]')
equal(o['a.a'], '[Redacted]')
})
test('child bindings are redacted using wildcard path', async ({ is }) => {
test('child bindings are redacted using wildcard path', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*.headers.cookie'] }, stream)
instance.child({
@ -756,10 +756,10 @@ test('child bindings are redacted using wildcard path', async ({ is }) => {
}
}).info('message completed')
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
})
test('child bindings are redacted using wildcard and plain path keys', async ({ is }) => {
test('child bindings are redacted using wildcard and plain path keys', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.method', '*.headers.cookie'] }, stream)
instance.child({
@ -772,6 +772,6 @@ test('child bindings are redacted using wildcard and plain path keys', async ({
}
}).info('message completed')
const { req } = await once(stream, 'data')
is(req.headers.cookie, '[Redacted]')
is(req.method, '[Redacted]')
equal(req.headers.cookie, '[Redacted]')
equal(req.method, '[Redacted]')
})

View File

@ -12,19 +12,19 @@ const childSerializers = {
test: () => 'child'
}
test('default err namespace error serializer', async ({ is }) => {
test('default err namespace error serializer', async ({ equal }) => {
const stream = sink()
const parent = pino(stream)
parent.info({ err: ReferenceError('test') })
const o = await once(stream, 'data')
is(typeof o.err, 'object')
is(o.err.type, 'ReferenceError')
is(o.err.message, 'test')
is(typeof o.err.stack, 'string')
equal(typeof o.err, 'object')
equal(o.err.type, 'ReferenceError')
equal(o.err.message, 'test')
equal(typeof o.err.stack, 'string')
})
test('custom serializer overrides default err namespace error serializer', async ({ is }) => {
test('custom serializer overrides default err namespace error serializer', async ({ equal }) => {
const stream = sink()
const parent = pino({
serializers: {
@ -38,47 +38,47 @@ test('custom serializer overrides default err namespace error serializer', async
parent.info({ err: ReferenceError('test') })
const o = await once(stream, 'data')
is(typeof o.err, 'object')
is(o.err.t, 'ReferenceError')
is(o.err.m, 'test')
is(typeof o.err.s, 'string')
equal(typeof o.err, 'object')
equal(o.err.t, 'ReferenceError')
equal(o.err.m, 'test')
equal(typeof o.err.s, 'string')
})
test('null overrides default err namespace error serializer', async ({ is }) => {
test('null overrides default err namespace error serializer', async ({ equal }) => {
const stream = sink()
const parent = pino({ serializers: { err: null } }, stream)
parent.info({ err: ReferenceError('test') })
const o = await once(stream, 'data')
is(typeof o.err, 'object')
is(typeof o.err.type, 'undefined')
is(typeof o.err.message, 'undefined')
is(typeof o.err.stack, 'undefined')
equal(typeof o.err, 'object')
equal(typeof o.err.type, 'undefined')
equal(typeof o.err.message, 'undefined')
equal(typeof o.err.stack, 'undefined')
})
test('undefined overrides default err namespace error serializer', async ({ is }) => {
test('undefined overrides default err namespace error serializer', async ({ equal }) => {
const stream = sink()
const parent = pino({ serializers: { err: undefined } }, stream)
parent.info({ err: ReferenceError('test') })
const o = await once(stream, 'data')
is(typeof o.err, 'object')
is(typeof o.err.type, 'undefined')
is(typeof o.err.message, 'undefined')
is(typeof o.err.stack, 'undefined')
equal(typeof o.err, 'object')
equal(typeof o.err.type, 'undefined')
equal(typeof o.err.message, 'undefined')
equal(typeof o.err.stack, 'undefined')
})
test('serializers override values', async ({ is }) => {
test('serializers override values', async ({ equal }) => {
const stream = sink()
const parent = pino({ serializers: parentSerializers }, stream)
parent.child({ serializers: childSerializers })
parent.fatal({ test: 'test' })
const o = await once(stream, 'data')
is(o.test, 'parent')
equal(o.test, 'parent')
})
test('child does not overwrite parent serializers', async ({ is }) => {
test('child does not overwrite parent serializers', async ({ equal }) => {
const stream = sink()
const parent = pino({ serializers: parentSerializers }, stream)
const child = parent.child({ serializers: childSerializers })
@ -86,13 +86,13 @@ test('child does not overwrite parent serializers', async ({ is }) => {
parent.fatal({ test: 'test' })
const o = once(stream, 'data')
is((await o).test, 'parent')
equal((await o).test, 'parent')
const o2 = once(stream, 'data')
child.fatal({ test: 'test' })
is((await o2).test, 'child')
equal((await o2).test, 'child')
})
test('Symbol.for(\'pino.serializers\')', async ({ is, isNot, deepEqual }) => {
test('Symbol.for(\'pino.serializers\')', async ({ equal, same, not }) => {
const stream = sink()
const expected = Object.assign({
err: stdSerializers.err
@ -100,9 +100,9 @@ test('Symbol.for(\'pino.serializers\')', async ({ is, isNot, deepEqual }) => {
const parent = pino({ serializers: parentSerializers }, stream)
const child = parent.child({ a: 'property' })
deepEqual(parent[Symbol.for('pino.serializers')], expected)
deepEqual(child[Symbol.for('pino.serializers')], expected)
is(parent[Symbol.for('pino.serializers')], child[Symbol.for('pino.serializers')])
same(parent[Symbol.for('pino.serializers')], expected)
same(child[Symbol.for('pino.serializers')], expected)
equal(parent[Symbol.for('pino.serializers')], child[Symbol.for('pino.serializers')])
const child2 = parent.child({
serializers: {
@ -114,22 +114,22 @@ test('Symbol.for(\'pino.serializers\')', async ({ is, isNot, deepEqual }) => {
return 'hello'
}
isNot(child2[Symbol.for('pino.serializers')], parentSerializers)
is(child2[Symbol.for('pino.serializers')].a, a)
is(child2[Symbol.for('pino.serializers')].test, parentSerializers.test)
not(child2[Symbol.for('pino.serializers')], parentSerializers)
equal(child2[Symbol.for('pino.serializers')].a, a)
equal(child2[Symbol.for('pino.serializers')].test, parentSerializers.test)
})
test('children inherit parent serializers', async ({ is }) => {
test('children inherit parent serializers', async ({ equal }) => {
const stream = sink()
const parent = pino({ serializers: parentSerializers }, stream)
const child = parent.child({ a: 'property' })
child.fatal({ test: 'test' })
const o = await once(stream, 'data')
is(o.test, 'parent')
equal(o.test, 'parent')
})
test('children inherit parent Symbol serializers', async ({ is, isNot, deepEqual }) => {
test('children inherit parent Symbol serializers', async ({ equal, same, not }) => {
const stream = sink()
const symbolSerializers = {
[Symbol.for('pino.*')]: parentSerializers.test
@ -139,7 +139,7 @@ test('children inherit parent Symbol serializers', async ({ is, isNot, deepEqual
}, symbolSerializers)
const parent = pino({ serializers: symbolSerializers }, stream)
deepEqual(parent[Symbol.for('pino.serializers')], expected)
same(parent[Symbol.for('pino.serializers')], expected)
const child = parent.child({
serializers: {
@ -152,13 +152,13 @@ test('children inherit parent Symbol serializers', async ({ is, isNot, deepEqual
return 'hello'
}
isNot(child[Symbol.for('pino.serializers')], symbolSerializers)
is(child[Symbol.for('pino.serializers')].a, a)
is(child[Symbol.for('pino.serializers')][Symbol.for('a')], a)
is(child[Symbol.for('pino.serializers')][Symbol.for('pino.*')], parentSerializers.test)
not(child[Symbol.for('pino.serializers')], symbolSerializers)
same(child[Symbol.for('pino.serializers')].a, a)
same(child[Symbol.for('pino.serializers')][Symbol.for('a')], a)
same(child[Symbol.for('pino.serializers')][Symbol.for('pino.*')], parentSerializers.test)
})
test('children serializers get called', async ({ is }) => {
test('children serializers get called', async ({ equal }) => {
const stream = sink()
const parent = pino({
test: 'this'
@ -168,10 +168,10 @@ test('children serializers get called', async ({ is }) => {
child.fatal({ test: 'test' })
const o = await once(stream, 'data')
is(o.test, 'child')
equal(o.test, 'child')
})
test('children serializers get called when inherited from parent', async ({ is }) => {
test('children serializers get called when inherited from parent', async ({ equal }) => {
const stream = sink()
const parent = pino({
test: 'this',
@ -182,10 +182,10 @@ test('children serializers get called when inherited from parent', async ({ is }
child.fatal({ test: 'fail' })
const o = await once(stream, 'data')
is(o.test, 'pass')
equal(o.test, 'pass')
})
test('non-overridden serializers are available in the children', async ({ is }) => {
test('non-overridden serializers are available in the children', async ({ equal }) => {
const stream = sink()
const pSerializers = {
onlyParent: function () { return 'parent' },
@ -203,14 +203,14 @@ test('non-overridden serializers are available in the children', async ({ is })
const o = once(stream, 'data')
child.fatal({ shared: 'test' })
is((await o).shared, 'child')
equal((await o).shared, 'child')
const o2 = once(stream, 'data')
child.fatal({ onlyParent: 'test' })
is((await o2).onlyParent, 'parent')
equal((await o2).onlyParent, 'parent')
const o3 = once(stream, 'data')
child.fatal({ onlyChild: 'test' })
is((await o3).onlyChild, 'child')
equal((await o3).onlyChild, 'child')
const o4 = once(stream, 'data')
parent.fatal({ onlyChild: 'test' })
is((await o4).onlyChild, 'test')
equal((await o4).onlyChild, 'test')
})

View File

@ -6,8 +6,8 @@ const { fork } = require('child_process')
const { once } = require('./helper')
const writer = require('flush-write-stream')
test('do not use SonicBoom is someone tampered with process.stdout.write', async ({ isNot }) => {
var actual = ''
test('do not use SonicBoom is someone tampered with process.stdout.write', async ({ not }) => {
let actual = ''
const child = fork(join(__dirname, 'fixtures', 'stdout-hack-protection.js'), { silent: true })
child.stdout.pipe(writer((s, enc, cb) => {
@ -15,5 +15,5 @@ test('do not use SonicBoom is someone tampered with process.stdout.write', async
cb()
}))
await once(child, 'close')
isNot(actual.match(/^hack/), null)
not(actual.match(/^hack/), null)
})

View File

@ -8,7 +8,7 @@ const { fork } = require('child_process')
const writer = require('flush-write-stream')
const { once, getPathToNull } = require('./helper')
test('asynchronous logging', async ({ is, teardown }) => {
test('asynchronous logging', async ({ equal, teardown }) => {
const now = Date.now
const hostname = os.hostname
const proc = process
@ -20,8 +20,8 @@ test('asynchronous logging', async ({ is, teardown }) => {
os.hostname = () => 'abcdefghijklmnopqr'
delete require.cache[require.resolve('../')]
const pino = require('../')
var expected = ''
var actual = ''
let expected = ''
let actual = ''
const normal = pino(writer((s, enc, cb) => {
expected += s
cb()
@ -33,14 +33,14 @@ test('asynchronous logging', async ({ is, teardown }) => {
}
const asyncLogger = pino(dest)
var i = 44
let i = 44
while (i--) {
normal.info('h')
asyncLogger.info('h')
}
var expected2 = expected.split('\n')[0]
var actual2 = ''
const expected2 = expected.split('\n')[0]
let actual2 = ''
const child = fork(join(__dirname, '/fixtures/syncfalse.js'), { silent: true })
child.stdout.pipe(writer((s, enc, cb) => {
@ -48,8 +48,8 @@ test('asynchronous logging', async ({ is, teardown }) => {
cb()
}))
await once(child, 'close')
is(actual, expected)
is(actual2.trim(), expected2)
equal(actual, expected)
equal(actual2.trim(), expected2)
teardown(() => {
os.hostname = hostname
@ -58,7 +58,7 @@ test('asynchronous logging', async ({ is, teardown }) => {
})
})
test('sync false with child', async ({ is, teardown }) => {
test('sync false with child', async ({ equal, teardown }) => {
const now = Date.now
const hostname = os.hostname
const proc = process
@ -74,8 +74,8 @@ test('sync false with child', async ({ is, teardown }) => {
}
delete require.cache[require.resolve('../')]
const pino = require('../')
var expected = ''
var actual = ''
let expected = ''
let actual = ''
const normal = pino(writer((s, enc, cb) => {
expected += s
cb()
@ -85,7 +85,7 @@ test('sync false with child', async ({ is, teardown }) => {
dest.write = function (s) { actual += s }
const asyncLogger = pino(dest).child({ hello: 'world' })
var i = 500
let i = 500
while (i--) {
normal.info('h')
asyncLogger.info('h')
@ -93,8 +93,8 @@ test('sync false with child', async ({ is, teardown }) => {
asyncLogger.flush()
var expected2 = expected.split('\n')[0]
var actual2 = ''
const expected2 = expected.split('\n')[0]
let actual2 = ''
const child = fork(join(__dirname, '/fixtures/syncfalse-child.js'), { silent: true })
child.stdout.pipe(writer((s, enc, cb) => {
@ -102,8 +102,8 @@ test('sync false with child', async ({ is, teardown }) => {
cb()
}))
await once(child, 'close')
is(actual, expected)
is(actual2.trim(), expected2)
equal(actual, expected)
equal(actual2.trim(), expected2)
teardown(() => {
os.hostname = hostname
@ -120,23 +120,23 @@ test('throw an error if extreme is passed', async ({ throws }) => {
})
test('flush does nothing with sync true (default)', async () => {
var instance = require('..')()
const instance = require('..')()
instance.flush()
})
test('pino.extreme() emits a warning', async ({ is }) => {
test('pino.extreme() emits a warning', async ({ equal }) => {
const pino = require('..')
process.removeAllListeners('warning')
process.nextTick(() => pino.extreme(0))
const warning = await once(process, 'warning')
const expected = 'The pino.extreme() option is deprecated and will be removed in v7. Use pino.destination({ sync: false }) instead.'
is(expected, warning.message)
is('extreme_deprecation', warning.code)
equal(expected, warning.message)
equal('extreme_deprecation', warning.code)
})
test('pino.extreme() defaults to stdout', async ({ is }) => {
test('pino.extreme() defaults to stdout', async ({ equal }) => {
const pino = require('..')
process.removeAllListeners('warning')
const dest = pino.extreme()
is(dest.fd, process.stdout.fd)
equal(dest.fd, process.stdout.fd)
})

View File

@ -14,7 +14,7 @@ test('pino exposes standard time functions', async ({ ok }) => {
ok(pino.stdTimeFunctions.isoTime)
})
test('pino accepts external time functions', async ({ is }) => {
test('pino accepts external time functions', async ({ equal }) => {
const opts = {
timestamp: () => ',"time":"none"'
}
@ -22,11 +22,11 @@ test('pino accepts external time functions', async ({ is }) => {
const instance = pino(opts, stream)
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), true)
is(result.time, 'none')
equal(result.hasOwnProperty('time'), true)
equal(result.time, 'none')
})
test('pino accepts external time functions with custom label', async ({ is }) => {
test('pino accepts external time functions with custom label', async ({ equal }) => {
const opts = {
timestamp: () => ',"custom-time-label":"none"'
}
@ -34,61 +34,61 @@ test('pino accepts external time functions with custom label', async ({ is }) =>
const instance = pino(opts, stream)
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('custom-time-label'), true)
is(result['custom-time-label'], 'none')
equal(result.hasOwnProperty('custom-time-label'), true)
equal(result['custom-time-label'], 'none')
})
test('inserts timestamp by default', async ({ ok, is }) => {
test('inserts timestamp by default', async ({ ok, equal }) => {
const stream = sink()
const instance = pino(stream)
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), true)
equal(result.hasOwnProperty('time'), true)
ok(new Date(result.time) <= new Date(), 'time is greater than timestamp')
is(result.msg, 'foobar')
equal(result.msg, 'foobar')
})
test('omits timestamp when timestamp option is false', async ({ is }) => {
test('omits timestamp when timestamp option is false', async ({ equal }) => {
const stream = sink()
const instance = pino({ timestamp: false }, stream)
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), false)
is(result.msg, 'foobar')
equal(result.hasOwnProperty('time'), false)
equal(result.msg, 'foobar')
})
test('inserts timestamp when timestamp option is true', async ({ ok, is }) => {
test('inserts timestamp when timestamp option is true', async ({ ok, equal }) => {
const stream = sink()
const instance = pino({ timestamp: true }, stream)
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), true)
equal(result.hasOwnProperty('time'), true)
ok(new Date(result.time) <= new Date(), 'time is greater than timestamp')
is(result.msg, 'foobar')
equal(result.msg, 'foobar')
})
test('child inserts timestamp by default', async ({ ok, is }) => {
test('child inserts timestamp by default', async ({ ok, equal }) => {
const stream = sink()
const logger = pino(stream)
const instance = logger.child({ component: 'child' })
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), true)
equal(result.hasOwnProperty('time'), true)
ok(new Date(result.time) <= new Date(), 'time is greater than timestamp')
is(result.msg, 'foobar')
equal(result.msg, 'foobar')
})
test('child omits timestamp with option', async ({ is }) => {
test('child omits timestamp with option', async ({ equal }) => {
const stream = sink()
const logger = pino({ timestamp: false }, stream)
const instance = logger.child({ component: 'child' })
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), false)
is(result.msg, 'foobar')
equal(result.hasOwnProperty('time'), false)
equal(result.msg, 'foobar')
})
test('pino.stdTimeFunctions.unixTime returns seconds based timestamps', async ({ is }) => {
test('pino.stdTimeFunctions.unixTime returns seconds based timestamps', async ({ equal }) => {
const opts = {
timestamp: pino.stdTimeFunctions.unixTime
}
@ -98,12 +98,12 @@ test('pino.stdTimeFunctions.unixTime returns seconds based timestamps', async ({
Date.now = () => 1531069919686
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), true)
is(result.time, 1531069920)
equal(result.hasOwnProperty('time'), true)
equal(result.time, 1531069920)
Date.now = now
})
test('pino.stdTimeFunctions.isoTime returns ISO 8601 timestamps', async ({ is }) => {
test('pino.stdTimeFunctions.isoTime returns ISO 8601 timestamps', async ({ equal }) => {
const opts = {
timestamp: pino.stdTimeFunctions.isoTime
}
@ -115,7 +115,7 @@ test('pino.stdTimeFunctions.isoTime returns ISO 8601 timestamps', async ({ is })
const iso = new Date(ms).toISOString()
instance.info('foobar')
const result = await once(stream, 'data')
is(result.hasOwnProperty('time'), true)
is(result.time, iso)
equal(result.hasOwnProperty('time'), true)
equal(result.time, iso)
Date.now = now
})