[logback-user] Logback code equivalent to adding log4j WriterAppender?

Fred Toth ftoth at synernet.com
Tue Dec 18 04:51:04 CET 2012


Hi folks,

I have a batch application that is using native log4j calls to capture 
WARN and ERROR events to a StringWriter, using their WriterAppender. At 
the end of the batch run, we retrieve the buffer and send an email.

I'm converting this to Logback and I've been looking for examples of how 
to do something similar. I don't really want to use SMTPAppender, 
because my existing email code is working and builds custom emails, 
handles address lists, etc.

I've got two problems, really:

1. What's the closest thing to WriterAppender with a StringWriter?
2. What's the simplest way to add this appender at runtime (startup)?

Can anyone point me to the Logback equivalent of this log4j code or 
suggest an alternative?

     static void initLogBuf() {
         Logger superLog = Logger.getLogger("org.project.my");

         Enumeration<Appender> e = Logger.getRootLogger().getAllAppenders();

         // Take the first layout we can find and use it
         Layout defaultLayout = null;
         while (e.hasMoreElements()) {
             Appender app = e.nextElement();
             defaultLayout = app.getLayout();
             break;
         }

         WriterAppender wApp = new WriterAppender();
         wApp.setWriter(logBufWriter);
         wApp.setName(LOG_BUF);
         wApp.setLayout(defaultLayout);
         wApp.setThreshold(Level.WARN);
         //log.info("WAPP: " + wApp.getThreshold());
         superLog.addAppender(wApp);
     }

Many thanks,

Fred



More information about the Logback-user mailing list