【问题标题】:Is it possible to segregate logger with name?是否可以用名称隔离记录器?
【发布时间】:2018-10-23 23:58:40
【问题描述】:

目前如果我运行 logger.debug('message') 我会得到这样的输出

{"message":"message","level":"debug"}

是否可以在创建记录器时做一些事情,使消息看起来更像这样?

{"message":"message","level":"debug","name":"someModule"}

最后我希望每个模块自定义自己的记录器,这样记录来自哪个模块就很清楚了

万一winston logger没有这个功能,你能推荐一个有这个功能的日志库吗?

【问题讨论】:

    标签: javascript node.js winston


    【解决方案1】:

    你可以使用custom-logger

    您可以在此处定义如下内容:

    var log = require('custom-logger').config({ format: "%message% %level%[%timestamp%]: %name%" });
    

    还有一些更复杂的东西,比如:

    log.new({
        alert: { level: 3, color: 'red', event: 'alert', format: '!!!!!%event% : %message% !!!!!' name: '%name%' }
    });
    

    而且很简单,比如:

    log.info("I see %d %s!", 3, "bananas"); 
    

    获取输出:输出“我看到 3 根香蕉!”

    对于您的具体问题,您可以将其添加到您的代码中:

    log.new({
       debug: { message: "This is the message" , level :"debug", name: "Your module name"}
    });
    

    使用库提供的标准:

    log.new({
           fatal: { message: "THIS IS THE END!" , level :"fatal", name: "Your module name"}
        });
    

    如果您想定义自己的颜色以获得更好的概览:

    log.info().config({ color: 'cyan' }); //This should be declared as global
    log.info('Hello World!');
    

    另外,你可以指定

    try {
      eval('alert("Hello world)');
    }
    catch(error) {
      console.error(error);
      log.new({
         error: { message: error, level :"error", name: "Your module name"}
      });
    }
    

    【讨论】:

    • 我喜欢自定义记录器,现在真正的问题是如何定义 %name?
    • @Tree 我更新了答案,以适合您的具体问题
    • 谢谢。如果我理解正确,我需要为每个级别创建 log.new,并在创建模块时在里面添加模块名称?
    • 是的,您也可以使用全局配置,例如:log.info().config({ color: 'cyan' });,并且每次都使用相同的配置,log.info('Hello World!'); 这个词将始终以青色显示。它对您有用,请将此答案作为正确答案。
    猜你喜欢
    • 2022-01-26
    • 2011-01-02
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多