简体   繁体   中英

log4j2 log file created even when Level is OFF?

I have a global logger which is used in a few classes so that I can log everything in a single file. All works good, however I want to be able to disable the Logger from UI. I tried setting the Level to OFF like shown below, which stops the logging but an empty log file is still created ( I am using File Appender with the logger).

Is there any easy way to avoid creating the log file when Level is OFF ?

public class Main {
    public static Logger LOGGER = LogManager.getLogger("GLOBAL");
    public static void main(String[] args) {
        Configurator.setLevel("GLOBAL", Level.OFF);
        //Rest of code

    }
}

The LogManager.getLogger("GLOBAL") creates the log file while reading the log4j configuration and initializing it. So, there is no way you can stop it from doing it when you are at Configurator.setLevel("GLOBAL", Level.OFF); . IMO, you have 2 options:

1) Elegant way : Initialize the LogManager in your code by passing the configuration at runtime LogManager.getLogManager().readConfiguration . You could refer here for detailed implementation.

2) Ugly way : Delete the log file when you set the LEVEL.OFF

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