【问题标题】:Node.js: How to change log level without restarting the server?Node.js:如何在不重新启动服务器的情况下更改日志级别?
【发布时间】:2019-05-18 13:32:36
【问题描述】:

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

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

【问题讨论】:

  • 如何在您的服务器中更改process.env.LOG_LEVEL?
  • 可以是任何可能的方式,1.在.bash_profile中修改2.使用导出命令3.通过docker image或Kubernetes仪表盘
  • 是的,但您必须重新启动该过程才能使更改生效。我没有看到任何其他方式。
  • 如果不是环境变量,有什么办法可以解决我的问题吗?
  • 事实上,我完全反对这样做。如果您可以按照自己的方式更改环境变量,您只会在应用程序中引入安全漏洞。配置应该是只读的和不可变的。如果需要更改,最好在 CI/CD 服务器上构建期间进行更改。

标签: node.js environment-variables winston loggly


【解决方案1】:

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

【讨论】:

  • 不错的解决方法!现在我会接受这个作为解决方案,但如果有更好的解决方案,我会选择它:P
  • 是的,我当然也愿意看到不同的方法。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
相关资源
最近更新 更多