tags:

views:

504

answers:

2

Hi,

I want to programmatically create a new log4j ConsoleAppender and add it as an appender to a logger - how do I go about instantiating one properly - using the following seems to make log4j complain - what setters do I need to use to configure it properly?

// log4j complains of "No output stream or file set for the appender named [null]."
logger.addAppender(new ConsoleAppender());

Presumably its a case of knowing what to set on the ConsoleAppender but I can't figure it out. I assume there's some way of getting the default layout. I just want a standard ConsoleAppender that appends to SysOut. Any guidance appreciated, thanks.

+2  A: 

This seems to be a known issue in log4j. You should be able to fix this either by calling activateOptions on the appender before adding it to the logger or by using a parameterized constructor for ConsoleAppender.

What version are you using? The bug seems to exist in a rather old version.

Ronald Wildenberg
+6  A: 

You will need to set a Writer on the appender (and then also a Layout in order to avoid the next error that you would see.) This means that you can't use an anonymous instance as you'll need to use the setters to configure the appender. e.g.

ConsoleAppender ca = new ConsoleAppender();
ca.setWriter(new OutputStreamWriter(System.out));
ca.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
logger.addAppender(ca);

Also, you can set the name of the appender with:

ca.setName("My appender");
mikej