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

Vad*_*dim 4 node.js pinojs

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

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

并有这个输出:
[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)
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

Ric*_*ams 5

我认为你能得到的最接近的如下:

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) });
Run Code Online (Sandbox Code Playgroud)

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


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

// logger.js
const logger = require('pino')({
  prettyPrint: {
    messageFormat: '{filename}: {msg}',
    ignore: 'pid,hostname,filename', 
  },
});
module.exports = logger;
Run Code Online (Sandbox Code Playgroud)
// file_with_logging.js
const parentLogger = require('./logger.js');
const logger = parentLogger.child({ filename: path.basename(__filename) });
Run Code Online (Sandbox Code Playgroud)