pino-pretty

repository·master·Indexed 23 days ago

https://github.com/pinojs/pino-pretty

An NDJSON formatter for Pino log lines designed for development use. It transforms standard Pino logs into human-readable, colorized output by interpreting log levels, timestamps, and error objects. It can be used as a CLI tool via piping, integrated programmatically as a Pino transport, or used as a stream. Version 13.1.3.

Tokens
4.6K
Snippets
9
Records
28
Agent score
76%

What's inside pino-pretty

  1. Use customPrettifiers to format log properties

    master

    The customPrettifiers option allows you to define custom formatting functions for specific log properties. This includes standard keys like time, hostname, pid, name, caller, and level, as well as any arbitrary key in your log object.

    Each prettifier function follows this signature: (output, keyName, logObj, extras) => string

    • output: The value of the property being prettified.
    • keyName: The name of the property.
    • logObj: The full log object.
    • extras: An object containing additional context. For level prettifiers, it includes label, labelColorized, and a colors object (a Colorette instance).
  2. Use pino-pretty as a stream

    master

    You can use pino-pretty as a stream by calling the pretty() function and passing the resulting stream to the pino constructor.

    If you need to provide Pino configuration options (like level) while using a stream, pass the Pino options as the first argument and the pino-pretty stream as the second argument.

  3. Handle non-serializable options via custom transport modules

    master

    When using Pino v7+ transports, options passed via the transport configuration must be serializable. If you need to use non-serializable options (such as a messageFormat function), you must wrap pino-pretty in a custom module that acts as the transport target.

    // main.js
    const pino = require('pino')
    
    const logger = pino({
      transport: {
        target: './pino-pretty-transport',
        options: {
          colorize: true
        }
      },
    })
    
    logger.info('world')
    // pino-pretty-transport.js
    module.exports = opts => require('pino-pretty')({
      ...opts,
      messageFormat: (log, messageKey) => `hello ${log[messageKey]}`
    })
  4. Use pino-pretty with Jest

    master

    Logging with Jest can be problematic because the framework requires no asynchronous operations to continue after a test finishes. To use pino-pretty with Jest, you must use the sync: true option to ensure logs are written synchronously.

    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');
    });
  5. Use pino-pretty by piping logs to the CLI

    master

    The recommended way to use pino-pretty is to pipe the output of your pino logger directly to the pino-pretty CLI tool in your terminal. This allows you to keep your application producing standard NDJSON logs while viewing prettified logs during development.

    node app.js | pino-pretty
  6. Integrate pino-pretty programmatically with Pino transports

    master

    To use pino-pretty within your application code, it is recommended to install it as a development dependency. You can integrate it using the Pino transport option by setting the target to 'pino-pretty'. You can also pass a configuration object to the options key to customize the output.

    Note: It is recommended to only activate pino-pretty when the output is a TTY (e.g., in development mode) to avoid performance issues in production.

    const pino = require('pino')
    const logger = pino({
      transport: {
        target: 'pino-pretty',
        options: {
          colorize: true
        }
      },
    })
    
    logger.info('hi')
  7. Customize pino-pretty output for Systemd logs

    master

    To make logs from journalctl more human-readable and remove redundant metadata, combine journalctl -o cat with specific pino-pretty flags:

    • -t: Formats the timestamp into a human-readable string.
    • -i <keys>: Filters out specific keys (like pid or hostname) from the output.

    Example command:

    journalctl -u monitor -f -o cat | pino-pretty -t -i pid,hostname

    This results in a clean, readable format such as: [2020-04-24 05:42:24.836 +0000] INFO : TT 21

  8. Avoid duplicate log data when using Systemd and journalctl

    master

    When running a Node.js process via Systemd and viewing logs with journalctl, metadata like timestamps, hostnames, and PIDs may appear twice: once from journalctl and once from pino-pretty.

    To prevent this duplication, use the -o cat option with journalctl to output only the raw log content before piping it to pino-pretty.

    Example workflow:

    1. Problematic (duplicated data): journalctl -u monitor -f | pino-pretty
    2. Correct (clean output): journalctl -u monitor -f -o cat | pino-pretty
    journalctl -u monitor -f -o cat | pino-pretty
  9. Load pino-pretty options from a JSON config file

    master

    Instead of passing many CLI arguments, you can specify a path to a JSON file containing your pino-pretty configuration using the -C or --config flag.

    cat log | pino-pretty --config=/path/to/config.json
  10. Configure pino-pretty via CLI arguments

    master

    The pino-pretty CLI supports a wide range of options to customize log formatting, including level detection, timestamp handling, and key filtering.

    Common Configuration Tasks

    • Custom Message Key: Highlight a string at a key other than msg using -m or --messageKey.
    • Custom Level Key: Detect the log level under a key other than level using -L or --levelKey.
    • Custom Level Label: Output the log level label using a key other than levelLabel using --levelLabel.
    • Custom Timestamp Key: Display the timestamp from a key other than time using -a or --timestampKey.
    • Timestamp Translation: Convert Epoch timestamps to ISO format using -t or --translateTime. Use the SYS: prefix for local timezone formats (e.g., -t "SYS:yyyy-mm-dd HH:MM:ss").
    • Filtering Fields: Use -i or --ignore to exclude specific keys (e.g., pid,hostname) or -I or --include to only show specific keys (e.g., time,level).
    • Minimum Log Level: Hide messages below a specific level using -L or --minimumLevel (e.g., -L info).
    • Reordering Fields: Use -l or --levelFirst to display the log level as the first output field.