tags:

views:

107

answers:

5

I want everything to log to the console and don't want to have to deal with creating log4j.xml files, etc. I am prototyping some libraries and want to see their full log output.

I would like to keep it as pure as possible and not have to introduce unnecessary dependencies like Spring, etc.

+1  A: 

It seems this does the trick.

import org.apache.log4j.BasicConfigurator;

public class Main {

    private static void initializeLogger() {
        BasicConfigurator.configure();
    }

    public static void main(String args[]) {
        Main.initializeLogger();
    }
}
Nick Stinemates
You can inline it. Just call BasicConfigurator.configure().
Thorbjørn Ravn Andersen
I just guarded from the future in case I want a more elaborate scheme.
Nick Stinemates
+1  A: 

The easiest way is to drop the following code into a file log4j.properties at the root of the classpath (i.e. your source or resources 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
Ramon
Downvoted because I specifically stated I don't want a log4j.xml (same as properties)
Nick Stinemates
I beg to differ - the XML-based configuration is far more cumbersome. The properties-based one is well-understood and highly conventional, doing anything else in code would only make it more difficult for other developers to understand what you're doing.
Ramon
I recommend consolidating your post with @rsp's to make a more concise and informative post.
Nick Stinemates
A: 

You can build up a Properties collection with the values needed and pass that to the PropertyConfigurator.configure(Properties) method.

rsp
+1  A: 

I use the following:

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

If you want to stay out of configuration files completely, you can do simple configuration in few lines like this :

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);
Dima