Programmatic configuration of Logback is really simple, when you know how. I'm not sure why they don't have more examples like this in the manual, because in some situations, its really important that logs don't get lost even if a configuration file isn't found (particularly when STDOUT goes nowhere). Anyway, here's one for you to get you started.
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;
FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>();
fa.setName("file");
fa.setFile("mylog.log");
LoggerContext con = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder pl = new PatternLayoutEncoder();
pl.setContext(con);
pl.setPattern("%d %5p %t [%c:%L] %m%n)");
pl.start();
fileAppender.setEncoder(pl);
fileAppender.start();
Logger rootLogger = con.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.addAppender(fa);
0 comments:
Post a Comment