Gathering detailed insights and metrics for pino-pretty
Gathering detailed insights and metrics for pino-pretty
Gathering detailed insights and metrics for pino-pretty
Gathering detailed insights and metrics for pino-pretty
npm install pino-pretty
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,270 Stars
411 Commits
150 Forks
11 Watching
4 Branches
101 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
JavaScript (99.2%)
TypeScript (0.8%)
Cumulative downloads
Total Downloads
Last day
-9.9%
739,349
Compared to previous day
Last week
1.3%
4,329,033
Compared to previous week
Last month
13.7%
17,633,121
Compared to previous month
Last year
57.6%
155,831,515
Compared to previous year
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
option
of pino
, read the Programmatic Integration section.
Using the example script from the Pino module, we can see what the prettified logs will look like:
1$ npm install -g pino-pretty
It is recommended to use pino-pretty
with pino
by piping output to the CLI tool:
1node app.js | pino-pretty
--colorize
(-c
): Adds terminal color escape sequences to the output.--colorizeObjects
(-C
): Allows suppressing colorization of objects when set to false
. In combination with --singleLine
, this ensures that the end of each line is parsable JSON.--crlf
(-f
): Appends carriage return and line feed, instead of just a line
feed, to the formatted log line.--errorProps
(-e
): When formatting an error object, display this list
of properties. The list should be a comma-separated list of properties Default: ''
.
Do not use this option if logging from pino@7. Support will be removed from future versions.--levelFirst
(-l
): Display the log level name before the logged date and time.--errorLikeObjectKeys
(-k
): Define the log keys that are associated with
error like objects. Default: err,error
.--messageKey
(-m
): Define the key that contains the main log message.
Default: msg
.--levelKey
(--levelKey
): Define the key that contains the level of the log. Nested keys are supported with each property delimited by a dot character (.
).
Keys may be escaped to target property names that contains the delimiter itself:
(--levelKey tags\\.level
).
Default: level
.--levelLabel
(-b
): Output the log level using the specified label.
Default: levelLabel
.--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/test
Default: false
--timestampKey
(-a
): Define the key that contains the log timestamp.
Default: time
.--translateTime
(-t
): Translate the epoch time value into a human-readable
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 dateformat
documentation.
HH:MM:ss.l
in the local timezone.UTC:
prefix to translate time to UTC, e.g. UTC:yyyy-mm-dd HH:MM:ss.l o
.SYS:
prefix to translate time to the local system's time zone. A
shortcut SYS:standard
to translate time to yyyy-mm-dd HH:MM:ss.l o
in
system time zone.--ignore
(-i
): Ignore one or several keys, nested keys are supported with each property delimited by a dot character (.
),
keys may be escaped to target property names that contains the delimiter itself:
(-i time,hostname,req.headers,log\\.domain\\.corp/foo
).
The --ignore
option would be ignored, if both --ignore
and --include
are passed.
Default: hostname
.--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 specifiedWe recommend against using pino-pretty
in production and highly
recommend installing pino-pretty
as a development dependency.
Install pino-pretty
alongside pino
and set the transport target to 'pino-pretty'
:
1const pino = require('pino') 2const logger = pino({ 3 transport: { 4 target: 'pino-pretty' 5 }, 6}) 7 8logger.info('hi')
The transport option can also have an options object containing pino-pretty
options:
1const pino = require('pino') 2const logger = pino({ 3 transport: { 4 target: 'pino-pretty', 5 options: { 6 colorize: true 7 } 8 } 9}) 10 11logger.info('hi')
Use it as a stream:
1const pino = require('pino') 2const pretty = require('pino-pretty') 3const logger = pino(pretty()) 4 5logger.info('hi')
Options are also supported:
1const pino = require('pino') 2const pretty = require('pino-pretty') 3const stream = pretty({ 4 colorize: true 5}) 6const logger = pino(stream) 7 8logger.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
,
pass the options as the first argument and pino-pretty
as second argument:
1const pino = require('pino') 2const pretty = require('pino-pretty') 3const stream = pretty({ 4 colorize: true 5}) 6const logger = pino({ level: 'info' }, stream) 7 8// Nothing is printed 9logger.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:
1import pino from 'pino' 2import pretty from 'pino-pretty' 3 4test('test pino-pretty', () => { 5 const logger = pino(pretty({ sync: true })); 6 logger.info('Info'); 7 logger.error('Error'); 8});
Using the new pino v7+
transports not all
options are serializable, for example if you want to use messageFormat
as a
function you will need to wrap pino-pretty
in a custom module.
Executing main.js
below will log a colorized hello world
message using a
custom function messageFormat
:
1// main.js 2const pino = require('pino') 3 4const logger = pino({ 5 transport: { 6 target: './pino-pretty-transport', 7 options: { 8 colorize: true 9 } 10 }, 11}) 12 13logger.info('world')
1// pino-pretty-transport.js 2module.exports = opts => require('pino-pretty')({ 3 ...opts, 4 messageFormat: (log, messageKey) => `hello ${log[messageKey]}` 5})
This boolean returns whether the currently used TTY supports colorizing the logs.
1import pretty from 'pino-pretty' 2 3if (pretty.isColorSupported) { 4 ... 5} 6
The options accepted have keys corresponding to the options described in CLI Arguments:
1{ 2 colorize: colorette.isColorSupported, // --colorize 3 colorizeObjects: true, //--colorizeObjects 4 crlf: false, // --crlf 5 errorLikeObjectKeys: ['err', 'error'], // --errorLikeObjectKeys (not required to match custom errorKey with pino >=8.21.0) 6 errorProps: '', // --errorProps 7 levelFirst: false, // --levelFirst 8 messageKey: 'msg', // --messageKey (not required with pino >=8.21.0) 9 levelKey: 'level', // --levelKey 10 messageFormat: false, // --messageFormat 11 timestampKey: 'time', // --timestampKey 12 translateTime: false, // --translateTime 13 ignore: 'pid,hostname', // --ignore 14 include: 'level,time', // --include 15 hideObject: false, // --hideObject 16 singleLine: false, // --singleLine 17 customColors: 'err:red,info:blue', // --customColors 18 customLevels: 'err:99,info:1', // --customLevels (not required with pino >=8.21.0) 19 levelLabel: 'levelLabel', // --levelLabel 20 minimumLevel: 'info', // --minimumLevel 21 useOnlyCustomProps: true, // --useOnlyCustomProps 22 // The file or file descriptor (1 is stdout) to write to 23 destination: 1, 24 25 // Alternatively, pass a `sonic-boom` instance (allowing more flexibility): 26 // destination: new SonicBoom({ dest: 'a/file', mkdir: true }) 27 28 // You can also configure some SonicBoom options directly 29 sync: false, // by default we write asynchronously 30 append: true, // the file is opened with the 'a' flag 31 mkdir: true, // create the target destination 32 33 34 customPrettifiers: {} 35}
The colorize
default follows
colorette.isColorSupported
.
The defaults for sync
, append
, mkdir
inherit from
SonicBoom(opts)
.
customPrettifiers
option provides the ability to add a custom prettify function
for specific log properties. customPrettifiers
is an object, where keys are
log properties that will be prettified and value is the prettify function itself.
For example, if a log line contains a query
property,
you can specify a prettifier for it:
1{ 2 customPrettifiers: { 3 query: prettifyQuery 4 } 5} 6//... 7const prettifyQuery = value => { 8 // do some prettify magic 9}
All prettifiers use this function signature:
1['logObjKey']: (output, keyName, logObj, extras) => string
logObjKey
- name of the key of the property in the log object that should have this function applied to itoutput
- the value of the property in the log objectkeyName
- the name of the property (useful for level
and message
when levelKey
or messageKey
is used)logObj
- the full log object, for contextextras
- an object containing additional data/functions created in the context of this pino-pretty logger or specific to the key (see level
prettifying below)
extras
objects contain colors
which is a Colorette object containing color functions. Colors are enabled based on colorize
provided to pino-pretty or colorette.isColorSupported
if colorize
was not provided.Additionally, customPrettifiers
can be used to format the time
, hostname
,
pid
, name
, caller
and level
outputs AS WELL AS any arbitrary key-value that exists on a given log object.
An example usage of customPrettifiers
using all parameters from the function signature:
1{ 2 customPrettifiers: { 3 // The argument for this function will be the same 4 // string that's at the start of the log-line by default: 5 time: timestamp => `🕰 ${timestamp}`, 6 7 // The argument for the level-prettifier may vary depending 8 // on if the levelKey option is used or not. 9 // By default this will be the same numerics as the Pino default: 10 level: logLevel => `LEVEL: ${logLevel}`, 11 // level provides additional data in `extras`: 12 // * label => derived level label string 13 // * labelColorized => derived level label string with colorette colors applied based on customColors and whether colors are supported 14 level: (logLevel, key, log, { label, labelColorized, colors }) => `LEVEL: ${logLevel} LABEL: ${levelLabel} COLORIZED LABEL: ${labelColorized}`, 15 16 // other prettifiers can be used for the other keys if needed, for example 17 hostname: hostname => `MY HOST: ${hostname}`, 18 pid: pid => pid, 19 name: (name, key, log, { colors }) => `${colors.blue(name)}`, 20 caller: (caller, key, log, { colors }) => `${colors.greenBright(caller)}`, 21 myCustomLogProp: (value, key, log, { colors }) => `My Prop -> ${colors.bold(value)} <--` 22 } 23}
messageFormat
option allows you to customize the message output.
A template string
like this can define the format:
1{ 2 messageFormat: '{levelLabel} - {pid} - url:{req.url}' 3}
In addition to this, if / end statement blocks can also be specified. Else statements and nested conditions are not supported.
1{ 2 messageFormat: '{levelLabel} - {if pid}{pid} - {end}url:{req.url}' 3}
This option can also be defined as a function
with this function signature:
1{ 2 messageFormat: (log, messageKey, levelLabel, { colors }) => { 3 // do some log message customization 4 // 5 // `colors` is a Colorette object with colors enabled based on `colorize` option 6 return `This is a ${color.red('colorized')}, custom message: ${log[messageKey]}`; 7 } 8}
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
No vulnerabilities found.
Reason
13 commit(s) and 6 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
Found 13/22 approved changesets -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More