'Node.js: How to change log level without restarting the server?

In the Node.js application, I use Winston for logging. Right now, the winston.level is set from process.env.LOG_LEVEL variable.

How to reset the winston.level whenever there is a change in process.env.LOG_LEVEL without restarting the Node process or server.



Solution 1:[1]

You can use debug npm module to do the trick. This code will help you to enable or disable debug logs without restarting your node application.

You can use debug module along with winston, where winston will log normal application logs, and for debugging you have to use this module.

/**
 *  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}`));

Note: This code might not be ready for production use

For security reason you should put this API behind Authentication and Authorization check.

Solution 2:[2]

@KamalakannanJ you might try to use RnR library to change winston log level on runtime without restarting the node server.

Here is the link: https://www.npmjs.com/package/runtime-node-refresh

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vinay Pandya
Solution 2 Przemek Nowicki