【问题标题】:Add MDC in Nodejs with log4j without requiring external libraries使用 log4j 在 Nodejs 中添加 MDC,无需外部库
【发布时间】:2017-01-26 22:21:02
【问题描述】:

我在 nodejs 中遇到了一个问题,我必须在元数据的日志中打印用户名。每个请求都有自己的用户名,并且 nodejs 是异步的,它覆盖了我为单例日志创建的用户名属性。

我已阅读有关 continous-local-storage 的信息,但我正在寻找一种更简单的解决方案,而不需要任何外部库。

是否建议为每个请求创建一个单独的日志实例?

P.S.:我是 Node js 的新手!!

【问题讨论】:

    标签: node.js log4j mdc


    【解决方案1】:

    只是一个更新,我想出了如何解决这个问题,但不得不依赖库 continous-local-storage。

    var myses= require('continuation-local-storage').createNamespace('myses');
    
    app.use(function (req, res, next) {
        myses.bindEmitter(req);
        myses.bindEmitter(res);
        myses.run(function () {
          myses.set('someid','somevalue');
          next();
            });
      });
    

    在其他文件中,比如自定义记录器,

    var thisSession = require('continuation-local-storage').getNamespace('myses');
    thisSession .get('someid');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多