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

3
在Node.js应用程序中,我使用Winston进行日志记录。目前,winston.levelprocess.env.LOG_LEVEL变量设置。如何在不重新启动Node进程或服务器的情况下,在process.env.LOG_LEVEL更改时重置winston.level

在你的服务器上,如何更改process.env.LOG_LEVEL - shanks
  1. 通过修改 .bash_profile 文件
  2. 使用 export 命令
  3. 通过 Docker 镜像或 Kubernetes 仪表板。
- Kamalakannan J
1
是的,但您必须重新启动该进程以使更改生效。我没有看到其他办法。 - shanks
如果没有环境变量,有没有其他方法来解决我的问题? - Kamalakannan J
我完全反对这样做。如果您可以按照自己的意愿更改环境变量,那么您只会在应用程序中引入安全漏洞。配置应该是只读和不可变的。如果需要更改,则最好在CI/CD服务器上进行构建时执行此操作。 - shanks
2个回答

3
你可以使用debug npm模块来达到目的。此代码将帮助您在不重新启动节点应用程序的情况下启用或禁用调试日志。
您可以使用带有winston的debug模块,其中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放置在身份验证授权检查后面。


好的解决方法!现在我会接受这个作为解决方案,但如果有更好的解决方案出现,我会选择它 :P - Kamalakannan J
1
是的,当然我也愿意看到不同的方法。 :) - Vinay Pandya
@VinayPandya,你认为使用Node进程来实现它怎么样?https://www.npmjs.com/package/runtime-node-refresh - Przemek Nowicki

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接