3

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

如何在不重新启动节点进程或服务器的情况下winston.level在发生更改时重置。process.env.LOG_LEVEL

4

1 回答 1

3

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

您可以将调试模块与 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 放在身份验证授权检查之后。

于 2020-01-22T08:37:58.630 回答