简体   繁体   中英

How to temporarily disable log4js logging in javascript?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM