title: Custom logging to gather messages at runtime
body: <p>Is there a way to create a log4j Logger at runtime that will gather logging messages into a buffer? </p>
  
  <p>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:</p>
  
  <pre><code>Class Foo{
     Logger log = ....;
  
     public void doSomething(){ 
        log.debug(...
        .. actual code
        log.debug(...
     }
  }
  </code></pre>
  
  <p>//what I'd like to do from some outside code:</p>
  
  <pre><code>String showFooLog(){
     Foo f = new Foo();
     f.log=new Logger(... 
     f.doSomething();
     return f.log.contents();
  }
  </code></pre>
  
  <h2>Is this possible?</h2>
  
  <p>Edit: Found a shorter solution, pointed to from Jared's posting( although it's still not threadsafe). Thanks for the help.</p>
  
  <pre><code> 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()
  </code></pre>