[logback-user] Programmatically add OutputStreamAppender to all loggers
Markos Fragkakis
markos.fragkakis at gmail.com
Tue May 21 22:19:24 CEST 2013
Hi,
I am building a simple web application that can be used to preview the
pattern layout of log files. The application aims to give you an idea of
what your log files will look like if you use a pattern layout.
Here you can see it working for the Log4j PatternLayout (still in progress):
http://log-preview.appspot.com/
Feel free to play around with, it is self explanatory.
I want to add support for Logback as well.
The idea is that I have a simple API, that is a servlet that receives a
pattern as a parameter. I then create an appender with that pattern layout
and attach it to the loggers of some classes. The appender actually appends
to the response stream, so the logs are actually the response of the API.
So, as I used a WriterAppender for log4j, I suppose an OutputStreamAppender
is the equivalent for Logback.
Unfortunately, I have not managed to append anything to the result stream.
Could you see what is wring with my code? It was dead simple with Log4j,
but I am still getting trouble here.
Thanks!
P.S. This is stripped down version that I think should be printing a log in
the response
package com.markos.logpreview;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.OutputStreamAppender;
@SuppressWarnings("serial")
public class Log_previewServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throwsIOException {
resp.setContentType("text/plain");
LoggerContext loggerContext = (LoggerContext)
LoggerFactory.getILoggerFactory();
loggerContext.reset();
OutputStreamAppender<ILoggingEvent> outputStreamAppender =
newOutputStreamAppender<ILoggingEvent>();
outputStreamAppender.setContext(loggerContext);
outputStreamAppender.setOutputStream(resp.getOutputStream());
PatternLayout pl = new PatternLayout();
pl.setPattern("%d %5p %t [%c:%L] %m%n)");
pl.setContext(loggerContext);
pl.start();
outputStreamAppender.setLayout(pl);
outputStreamAppender.start();
Logger logbackLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
logbackLogger.addAppender(outputStreamAppender);
* logbackLogger.error("I should show up in the response!");*
}
}
--
Sent from my iPhone
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qos.ch/pipermail/logback-user/attachments/20130521/3cabd54a/attachment.html>
More information about the Logback-user
mailing list