Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a new log4j ConsoleAppender in code as opposed to config?

Tags:

java

log4j

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.

like image 628
Supertux Avatar asked Sep 07 '09 13:09

Supertux


People also ask

How do I change the log4j configuration at runtime?

Use LogManager. resetConfiguration(); to clear the current config and configure it again. Another approach is to build a new appender and replace the old one with it (most appenders don't support changing their config).

What is log4j ConsoleAppender?

ConsoleAppender, Java Logging. Log4j2 ConsoleAppender appends the log events generated by application into the System. out or System.


2 Answers

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");
like image 118
mikej Avatar answered Sep 18 '22 15:09

mikej


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.

like image 32
Ronald Wildenberg Avatar answered Sep 18 '22 15:09

Ronald Wildenberg