6

i need to add file name to pino-pretty line output,
now i'm using:

const pino = require('pino');
const logger = pino({
    prettyPrint: {
        colorize: true,
        translateTime: 'yyyy-mm-dd HH:MM:ss',
        ignore: 'pid,hostname'
    }
})

and have this output:
[2020-05-14 16:25:45] INFO : Network is private

but i want something like this:
[2020-05-14 16:25:45] INFO myFile.js: Network is private

i.e. i want see filename in line witch was launch, i try play with customPrettifiers option but can't get hoped result,
for example i try this:

const pino = require('pino');
const path = require('path');
const logger = pino({
    prettyPrint: {
        colorize: true,
        translateTime: 'yyyy-mm-dd HH:MM:ss',
        ignore: 'pid,hostname',
        customPrettifiers: {
            filename: path.basename(__filename)
        }
    }
})
Vadim
  • 402
  • 6
  • 15

1 Answers1

6

I think the closest you can get is as follows:

const path = require('path');
const pino = require('pino');
const logger = pino({
  prettyPrint: {
    // Adds the filename property to the message
    messageFormat: '{filename}: {msg}',

    // need to ignore 'filename' otherwise it appears beneath each log
    ignore: 'pid,hostname,filename', 
  },
}).child({ filename: path.basename(__filename) });

Note that you can't style the filename differently to the message, but hopefully that's good enough.


It's probably also better to have a separate logger.js file where the default pino options are passed e.g.:

// logger.js
const logger = require('pino')({
  prettyPrint: {
    messageFormat: '{filename}: {msg}',
    ignore: 'pid,hostname,filename', 
  },
});
module.exports = logger;
// file_with_logging.js
const parentLogger = require('./logger.js');
const logger = parentLogger.child({ filename: path.basename(__filename) });
Richard Williams
  • 2,044
  • 1
  • 24
  • 28
  • 1
    This comment was super helpful to me. However, if anyone else lands here, I found it much easier to set the filename to the property `name` in the child options. This prevents you from needing to use a custom message format and moves the filename to the left of the message. If you're colorizing, it'll also be a different color than the message itself. – Kyle Dec 21 '20 at 15:40
  • @Kyle I'm not seeing `name` as a valid option when creating a child -- https://github.com/pinojs/pino/blob/42dde2af3e012bcfc6ff23ece2393dc24f8ee1b7/pino.d.ts#L602-L612 – slifty Jul 27 '22 at 14:02