在node.js应用程序中,我使用winston进行登录。目前,winston.level
是从process.env.LOG_LEVEL
变量设置的。
每当process.env.LOG_LEVEL
发生更改而不重新启动节点过程或服务器时,如何重置winston.level
。
您可以使用 debug npm模块来完成技巧。此代码将帮助您无需重新启动节点应用程序即可启用或禁用调试日志。
您可以与Winston一起使用 debug 模块,温斯顿将记录正常应用程序日志,并且要调试您必须使用此模块。
/**
* 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放在身份验证和授权检查
@kamalakannanj您可以尝试使用 rnr 库在不重新启动节点服务器的情况下更改运行时的Winston日志级别。
这是链接:https://www.npmjs.com/package/runtime-node-refresh