【问题标题】:pino-pretty, how to add file name to log linepino-pretty,如何将文件名添加到日志行
【发布时间】:2020-08-31 07:50:23
【问题描述】:

我需要将文件名添加到 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)
        }
    }
})

【问题讨论】:

    标签: node.js pinojs


    【解决方案1】:

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

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

    【讨论】:

    • 这条评论对我很有帮助。但是,如果其他人在这里登陆,我发现在子选项中将文件名设置为属性 name 会容易得多。这可以防止您需要使用自定义消息格式并将文件名移动到消息的左侧。如果您正在着色,它也将是与消息本身不同的颜色。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多