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.
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).
ConsoleAppender, Java Logging. Log4j2 ConsoleAppender appends the log events generated by application into the System. out or System.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With