Sometimes you may need to integrate debug with a high performance logger, such as pino. And of course, there is an NPM package for that.

However, if you look at its source code, you will find out that it uses undocumented dirty hacks, which, in my opinion, make it quite fragile.

When I looked at its source code, I asked myself if it were possible to make it simpler. And the answer is yes — this is possible at least since debug 1.0.0 (that is, June 2014).

debug exports log() method, which performs — surprise! — logging. And — surprise! — it is possible to override it.

So,

const dbg = require('debug');
const pino = require('pino');
const util = require('util');

const logger = pino({ /* pino options go here */ });
dbg.log = function(s, ...args) {
  // If you use logger.debug() like I do,
  // you may need to pass <code>{{EJS5}}</code>
  // to pino constructor
  logger.debug(util.format(s, ...args));
};

Depending on your environment, you may want to disable colors: dbg.inspectOpts.colors = false; (this will work for debug >= 2)

This simple example does not handle the opts.map feature of pino-debug, yet it is very easy to implement. log() function receives the following object as its this object:

{
  namespace: 'ns',    // This can be used to map namespaces to different log levels
  enabled: true,      // Whether this namespace is enabled; unless I miss something, it will always be true
  useColors: false,   // Whether to use colors
  color: 5,           // Color number
  inspectOpts: { colors: false }, // Options that were passed to util.inspect()
  diff: 0,            // Millisecond diff - https://www.npmjs.com/package/debug#user-content-millisecond-diff
  prev: undefined,    // Previous timestamp
  curr: 1564700248687 // Timestamp
}

All properties in the object above are informative: they merely tell which settings were used to create the message log() function is about to log.

And there is no need to apply weird hacks to make debug and pino work together 🙂

Easy Way to Make pino and debug Work Together
Tagged on:                     

Leave a Reply

Your email address will not be published. Required fields are marked *