Is there a way to create a log4j Logger at runtime that will gather logging messages into a buffer?
I currently have a class that logs a number of events. For a remote application that needs to monitor the logged events, I'd like to just swap in a logger that logs to a buffer and then retrieve the buffer, rather than refactor the class. E.g. given something like:
Class Foo{
Logger log = ....;
public void doSomething(){
log.debug(...
.. actual code
log.debug(...
}
}
//what I'd like to do from some outside code:
String showFooLog(){
Foo f = new Foo();
f.log=new Logger(...
f.doSomething();
return f.log.contents();
}
Is this possible?
Edit: Found a shorter solution, pointed to from Jared's posting( although it's still not threadsafe). Thanks for the help.
Logger l = Logger.getLogger( ... );
StringWriter writer = new StringWriter();
WriterAppender appender = new WriterAppender( new HTMLLayout(), writer );
l.addAppender( appender );
... run code here
writer.flush();
l.removeAppender( appender );
return writer.toString()