Node.js: 如何在不重启服务器的情况下更改日志级别?

Node.js: How to change log level without restarting the server?

在 Node.js 应用程序中,我使用 Winston 进行日志记录。现在,winston.level 是从 process.env.LOG_LEVEL 变量设置的。

如何在 process.env.LOG_LEVEL 发生变化时重置 winston.level 而无需重新启动节点进程或服务器。

您可以使用 debug npm 模块来解决这个问题。此代码将帮助您在不重新启动节点应用程序的情况下启用或禁用调试日志。

您可以将 debug 模块与 winston 一起使用,其中 winston 将记录正常的应用程序日志,并且要进行调试,您必须使用此模块。

/**
 *  To test this code 
 *  1. npm install debug express and npm start = to run a server
 *  2. goto http://localhost:8181/ = (simmulate running batch process) to start the logging on every second
 *  3. goto http://localhost:8181/change/myapp:db = to eable debug log
 *  4. goto http://localhost:8181/disable = to disable debug log
 * 
 *  Note: Don't foget to monitor your console, after each request. :P
 */
const debug = require('debug');
const express = require('express');

const intiLog = debug('myapp:init');
const batchProcessLog = debug('myapp:batch');
const dbLog = debug('myapp:db');

const app = express();

app.get('/', (req, res) => {
    setInterval(() => {
        console.log('This normal console.log');
        intiLog('This is init log');
        batchProcessLog('Hey this is batch process');
        dbLog('This is DB logs');
    }, 1000);
    return res.status(200).send('OK');
});

// nameSpance = myapp:init => enable only one log
// nameSpace = myapp:db,myapp:myappbatch => enable multiple log
// nameSpace = myapp:*,-myapp:init => enable all log except myapp:init log
app.get('/change/:nameSpace', (req, res) => {
    const { nameSpace } = req.params;
    debug.enable(nameSpace);
    return res.status(200).send(`May the force be with you ${nameSpace}`);
});

app.get('/disable', (req, res) => {
    debug.disable();    
    return res.status(200).send(`See you than...`);
});


app.listen(8181, () => console.log(`Running app on ${8181}`));

注意:此代码可能无法用于生产

出于安全原因,您应该将此 API 置于 AuthenticationAuthorization 检查之后。

@KamalakannanJ 您可能会尝试使用 RnR 库在运行时更改 winston 日志级别,而无需重新启动节点服务器。

这是 link: https://www.npmjs.com/package/runtime-node-refresh