What is the shortest way to initialize log4j in your main method?

I want everything to go into the console and not want to deal with creating log4j.xml files, etc. I am prototyping some libraries and want to see their full magazine output.

I would like to keep it as clean as possible, and no need to introduce unnecessary dependencies like Spring, etc.

+4
source share
5 answers

I am using the following:

Logger.getRootLogger().setLevel(Level.ALL); Layout layout = new PatternLayout("%d [%t] %-5p %c %x - %m%n"); Logger.getRootLogger().addAppender(new ConsoleAppender(layout)); 
+6
source

This seems to be a trick.

 import org.apache.log4j.BasicConfigurator; public class Main { private static void initializeLogger() { BasicConfigurator.configure(); } public static void main(String args[]) { Main.initializeLogger(); } } 
+1
source

The easiest way is to dump the following code into the log4j.properties file at the root of the class path (for example, to the source or resource folder):

 log4j.rootLogger=info, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=[%p] %c{2} %m%n 
+1
source

If you want to completely disconnect from the configuration files, you can do a simple configuration in several lines, for example:

 Properties props = new Properties(); props.setProperty("log4j.appender.CONSOLE",org.apache.log4j.ConsoleAppender"); props.setProperty("log4j.appender.CONSOLE.Threshold", "TRACE"); props.setProperty("log4j.appender.CONSOLE.layout,"org.apache.log4j.PatternLayout"); props.setProperty("log4j.appender.CONSOLE.layout.ConversionPattern","%-5p %d{HH:mm:ss} %-30C{1} | %m%n);" props.setProperty("log4j.rootLogger", "TRACE, CONSOLE"); PropertyConfigurator.configure(props); 
+1
source

You can create a Properties collection with the necessary values ​​and pass this to the PropertyConfigurator.configure(Properties) method.

0
source

All Articles