I want to intercept this error so that it would be possible to “substitute” the log4j configuration for the case of “default”, when the standard configuration file was not found where it was supposed to be. Is it possible
- This is not a mistake, but a varning. - raviga
- It is necessary not to intercept, but to write your own implementation of the class that configures log4j, in which it is just to check the presence of a standard file, and if it is not present, substitute the default one. - enzo
- @enzo, are there any examples, something to read on this topic? - Igor Kudryashov
- This is a question for a psychic show. :) You did not specify either the log4j version, or what application you have, and who initializes the logger. You need to read the log4j documentation and your framework, if any. - enzo
|
1 answer
You can hide WARNIG (No appenders ...) in case of missing file and load default configurations:
public static Logger log = Logger.getLogger(Main.class); public static void main(String[] args) { URL propertiesUrl = Main.class.getResource("/log4j.properties"); if (propertiesUrl == null) { //Hide no appender warning Logger.getRootLogger().setLevel(Level.OFF); log.info("Load default logger properties"); updateLog4jConfiguration(); log.info("Default logger properties are loaded"); } log.info("Main method is started."); } private static void updateLog4jConfiguration() { Properties props = new Properties(); try (InputStream configStream = Main.class.getResourceAsStream( "/default.properties")) { props.load(configStream); } catch (IOException e) { System.out.println("Errornot laod configuration file "); } LogManager.resetConfiguration(); PropertyConfigurator.configure(props); }
To hide WARNIN Logger.getRootLogger (). SetLevel (Level.OFF); must be called before the first message in the log, otherwise we will see WARNING in stderr. I used something like the default configuration:
# Root logger option log4j.rootLogger=ERROR, stdout # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n log4j.logger.my.test.logger=INFO
You can see that after updating the properties, the logs start to be output to stdout.
|