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

时间:2018-12-18 07:00:54

标签: node.js environment-variables winston loggly

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

winston.level中发生更改时如何重置process.env.LOG_LEVEL,而无需重新启动Node进程或服务器。

1 个答案:

答案 0 :(得分:2)

您可以使用 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放在 Authentication Authorization 检查之后。