pino-pretty,如何将文件名添加到日志行

pino-pretty, how to add file name to log line

我需要将文件名添加到 pino-pretty 行输出,
现在我正在使用:

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

并有这个输出:
[2020-05-14 16:25:45] INFO : Network is private

但我想要这样的东西:
[2020-05-14 16:25:45] INFO myFile.js: Network is private

即我想查看 行中的文件名已启动,我尝试使用 customPrettifiers 选项但无法获得希望的结果,
例如我试试这个:

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)
        }
    }
})

我认为最接近的如下:

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) });

请注意,您不能将文件名的样式设置为与消息不同,但希望这就足够了。


最好有一个单独的 logger.js 文件来传递默认的 pino 选项,例如:

// 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) });