如何req.user.id使用log4js在node js的每个日志语句中打印www.example.com

jslywgbw  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(157)

目前,我在任何route文件中使用express和log4js模块,如下所示:

var log = require('log4jslogger.js').LOG;
log.info('this is log statement');

日志记录器.js

var log4js = require('log4js');
log4js.configure(__base + "log4jsconfig.json");

var logger = log4js.getLogger('default');
Object.defineProperty(exports, "LOG", {
    value : logger,
});

日志4jsconfig.json

{
    "appenders": {
        "out": {
            "type": "stdout"
        },
        "default": {
            "type": "dateFile",
            "filename": "logs/default",
            "pattern": "-yyyy-MM-dd.log",
            "alwaysIncludePattern": true,
            "keepFileExt": true
        }
    },
    "categories": {
        "default": {
            "appenders": ["out",
            "default"],
            "level": "trace"
        }
    }
}

我想在所有日志语句中添加日志记录的[username][unauthenticated]。我可以像req.user.id那样获得。
我们如何才能做到这一点,而不是添加到所有日志语句?
在log4js文档中,我发现了一个使用标记的布局用法,但没有弄清楚如何形成AuthLibrary.currentUser()

14ifxucb

14ifxucb1#

const currentUser = require("./authLibrary").currentUser;
log4js.configure({
    replaceConsole: true,
    appenders: {
        stdout: {
            type: 'console',
            layout: {
                type: "pattern",
                pattern: "%d %p %c %x{user} %m%n",
                tokens: {
                    user: function (logEvent) {
                        return `[auth:${currentUser().UserName || '-'} / ${currentUser().UserId || '-'}]`;
                    },
                },
            },
        }
    },
    categories: { default: { appenders: ['stdout'], level: 'info' }, },
});

//认证库. js

let user = {};

const setCurrentUser = (_user) => {
    user = _user;
}
const currentUser = () => user;
module.exports = { currentUser, setCurrentUser };

//测试

(async (err, req, res, next) => {
    const token = req.get('token')
    const user = await authService(token)
    req.currentUser = user;
    require("../utils/authLibrary").setCurrentUser(user);
})(null, { get: (x) => "1697E29ADE8DA9F6F84E214CF66E" }, null, null)

相关问题