How to temporarily disable log4js logging in javascript?

Viewed 1174

There are a few third party libraries that are using log4js to output their logs. I know it sounds counter-intuitive but I would like to disable these logs temporarily to be able to investigate an issue that I have.

How do I temporarily disable log4js logs temporarily in code in javascript? Specifically nodejs.

2 Answers

In log4js 5.3.0 (not sure how many versions back it's the same) you can do this by turning everything off temporarily at the root logger, which affects every other logger:

log4js.getLogger().level = 'off';

A full example:

#!/bin/env node

const log4js = require('log4js');

log4js.configure({
    appenders: {
        out: { type: "stdout" }
    },
    categories: {
        default: {
            appenders: [ "out" ],
            level: "info"
        }
    }
});

const rootLogger = log4js.getLogger();

const log = log4js.getLogger('foo');

log.info('this is on - turning off');

rootLogger.level = 'off';

log.info('this is off - turning back on');

rootLogger.level = 'info';

log.info('this is back on');

Which gives you:

[2019-11-13T22:00:37.541] [INFO] foo - this is on - turning off
[2019-11-13T22:00:37.544] [INFO] foo - this is back on

In the app.js file of my nodejs application I place the following code to temporarily disable log4js logs from thirdparty libraries.

const log4js = require('log4js')
log4js.configure({})

This works for disabling the logs.

Related