Prettifier for Pino log lines in browser




This module provides a basic ndjson formatter to be used in __development__. If an
incoming line looks like it could be a log line from an ndjson logger, in
particular the Pino logging library, then it will apply
extra formatting by considering things like the log level and timestamp.
A standard Pino log line like:
```
{"level":30,"time":1522431328992,"msg":"hello world","pid":42,"hostname":"foo","v":1}
Will format to:
``
[17:35:28.992] INFO (42): hello world
If you landed on this page due to the deprecation of the prettyPrint optionpino
of , read the Programmatic Integration section.
Using the [example script][exscript] from the Pino module, we can see what the
prettified logs will look like:
!demo
[exscript]: https://github.com/pinojs/pino/blob/25ba61f40ea5a1a753c85002812426d765da52a4/examples/basic.js
`sh`
$ npm install -g pino-pretty
It is recommended to use pino-pretty with pino
by piping output to the CLI tool:
`sh`
node app.js | pino-pretty
- --colorize (-c): Adds terminal color escape sequences to the output.--crlf
- (-f): Appends carriage return and line feed, instead of just a line--errorProps
feed, to the formatted log line.
- (-e): When formatting an error object, display this list''
of properties. The list should be a comma-separated list of properties Default: .--levelFirst
Do not use this option if logging from pino@7. Support will be removed from future verions.
- (-l): Display the log level name before the logged date and time.--errorLikeObjectKeys
- (-k): Define the log keys that are associated witherr,error
error like objects. Default: .--messageKey
- (-m): Define the key that contains the main log message.msg
Default: .--levelKey
- (--levelKey): Define the key that contains the level of the log.level
Default: .--levelLabel
- (-b): Output the log level using the specified label.levelLabel
Default: .--minimumLevel
- (-L): Hide messages below the specified log level. Accepts a number, trace, debug, info, warn, error, or fatal. If any more filtering is required, consider using jq.--customLevels
- (-x): Override default levels with custom levels, e.g. -x err:99,info:1--customColors
- (-X): Override default colors with custom colors, e.g. -X err:red,info:blue--useOnlyCustomProps
- (-U): Only use custom levels and colors (if provided) (default: true); else fallback to default levels and colors, e.g. -U false--messageFormat
- (-o): Format output of message, e.g. {levelLabel} - {pid} - url:{req.url} will output message: INFO - 1123 - url:localhost:3000/testfalse
Default: --timestampKey
- (-a): Define the key that contains the log timestamp.time
Default: .--translateTime
- (-t): Translate the epoch time value into a human-readabledateformat
date and time string. This flag also can set the format string to apply when
translating the date to a human-readable format. For a list of available pattern
letters, see the documentation.HH:MM:ss.l
- The default format is in the local timezone.UTC:
- Require a prefix to translate time to UTC, e.g. UTC:yyyy-mm-dd HH:MM:ss.l o.SYS:
- Require a prefix to translate time to the local system's time zone. ASYS:standard
shortcut to translate time to yyyy-mm-dd HH:MM:ss.l o in--ignore
system time zone.
- (-i): Ignore one or several keys, nested keys are supported with each property delimited by a dot character (.),-i time,hostname,req.headers,log\\.domain\\.corp/foo
keys may be escaped to target property names that contains the delimiter itself:
().--ignore
The option would be ignored, if both --ignore and --include are passed.hostname
Default: .--include
- (-I): The opposite of --ignore. Include one or several keys.--hideObject
- (-H): Hide objects from output (but not error object)--singleLine
- (-S): Print each log message on a single line (errors will still be multi-line)--config
- : Specify a path to a config file containing the pino-pretty options. pino-pretty will attempt to read from a .pino-prettyrc in your current directory (process.cwd) if not specified
We recommend against using pino-pretty in production and highlypino-pretty
recommend installing as a development dependency.
Install pino-pretty alongside pino and set the transport target to 'pino-pretty':
`js
const pino = require('pino')
const logger = pino({
transport: {
target: 'pino-pretty'
},
})
logger.info('hi')
`
The transport option can also have an options object containing pino-pretty options:
`js
const pino = require('pino')
const logger = pino({
transport: {
target: 'pino-pretty',
options: {
colorize: true
}
}
})
logger.info('hi')
`
Use it as a stream:
`js
const pino = require('pino')
const pretty = require('pino-pretty')
const logger = pino(pretty())
logger.info('hi')
`
Options are also supported:
`js
const pino = require('pino')
const pretty = require('pino-pretty')
const stream = pretty({
colorize: true
})
const logger = pino(stream)
logger.info('hi')
`
See the Options section for all possible options.
If you are using pino-pretty as a stream and you need to provide options to pino,pino-pretty
pass the options as the first argument and as second argument:
`js
const pino = require('pino')
const pretty = require('pino-pretty')
const stream = pretty({
colorize: true
})
const logger = pino({ level: 'info' }, stream)
// Nothing is printed
logger.debug('hi')
`
Logging with Jest is _problematic_, as the test framework requires no asynchronous operation to
continue after the test has finished. The following is the only supported way to use this module
with Jest:
`js
import pino from 'pino'
import pretty from 'pino-pretty'
test('test pino-pretty', () => {
const logger = pino(pretty({ sync: true }));
logger.info('Info');
logger.error('Error');
});
`
Using the new pino v7+
transports not all
options are serializable, for example if you want to use messageFormat as apino-pretty
function you will need to wrap in a custom module.
Executing main.js below will log a colorized hello world message using amessageFormat
custom function :
`js
// main.js
const pino = require('pino')
const logger = pino({
transport: {
target: './pino-pretty-transport',
options: {
colorize: true
}
},
})
logger.info('world')
`
`jshello ${log[messageKey]}
// pino-pretty-transport.js
module.exports = opts => require('pino-pretty')({
...opts,
messageFormat: (log, messageKey) => `
})
The options accepted have keys corresponding to the options described in CLI Arguments:
`js
{
colorize: colorette.isColorSupported, // --colorize
crlf: false, // --crlf
errorLikeObjectKeys: ['err', 'error'], // --errorLikeObjectKeys
errorProps: '', // --errorProps
levelFirst: false, // --levelFirst
messageKey: 'msg', // --messageKey
levelKey: 'level', // --levelKey
messageFormat: false, // --messageFormat
timestampKey: 'time', // --timestampKey
translateTime: false, // --translateTime
ignore: 'pid,hostname', // --ignore
include: 'level,time', // --include
hideObject: false, // --hideObject
singleLine: false, // --singleLine
config: '/path/to/config/', // --config
customColors: 'err:red,info:blue', // --customColors
customLevels: 'err:99,info:1', // --customLevels
levelLabel: 'levelLabel', // --levelLabel
minimumLevel: 'info', // --minimumLevel
useOnlyCustomProps: true, // --useOnlyCustomProps
// The file or file descriptor (1 is stdout) to write to
destination: 1,
// Alternatively, pass a sonic-boom instance (allowing more flexibility):
// destination: new SonicBoom({ dest: 'a/file', mkdir: true })
// You can also configure some SonicBoom options directly
sync: false, // by default we write asynchronously
append: true, // the file is opened with the 'a' flag
mkdir: true, // create the target destination
customPrettifiers: {}
}
`
The colorize default followscolorette.isColorSupported.
The defaults for sync, append, mkdir inherit fromSonicBoom(opts).
customPrettifiers option provides the ability to add a custom prettify functioncustomPrettifiers
for specific log properties. is an object, where keys arequery
log properties that will be prettified and value is the prettify function itself.
For example, if a log line contains a property,
you can specify a prettifier for it:
`js`
{
customPrettifiers: {
query: prettifyQuery
}
}
//...
const prettifyQuery = value => {
// do some prettify magic
}
Additionally, customPrettifiers can be used to format the time, hostname, pid, name, caller and level
outputs:
`js🕰 ${timestamp}
{
customPrettifiers: {
// The argument for this function will be the same
// string that's at the start of the log-line by default:
time: timestamp => ,
// The argument for the level-prettifier may vary depending
// on if the levelKey option is used or not.
// By default this will be the same numerics as the Pino default:
level: logLevel => LEVEL: ${logLevel}
// other prettifiers can be used for the other keys if needed, for example
hostname: hostname => colorGreen(hostname)
pid: pid => colorRed(pid)
name: name => colorBlue(name)
caller: caller => colorCyan(caller)
}
}
`
Note that prettifiers do not include any coloring, if the stock coloring on
level is desired, it can be accomplished using the following:
`jsLEVEL: ${levelColorize(logLevel)}
const { colorizerFactory } = require('pino-pretty')
const levelColorize = colorizerFactory(true)
const levelPrettifier = logLevel => `
//...
{
customPrettifiers: { level: levelPrettifier }
}
messageFormat option allows you to customize the message output. A template string like this can define the format:
`js`
{
messageFormat: '{levelLabel} - {pid} - url:{req.url}'
}
This option can also be defined as a function with this prototype:
`js`
{
messageFormat: (log, messageKey, levelLabel) => {
// do some log message customization
return customized_message;
}
}
Because pino-pretty uses stdout redirection, in some cases the command may
terminate with an error due to shell limitations.
For example, currently, mingw64 based shells (e.g. Bash as supplied by git for
Windows) are affected and terminate the process with
a stdout is not a tty` error message.
Any PRs are welcomed!
MIT License