Created
June 25, 2015 17:36
-
-
Save sangupta/c41fc31ed949e5cda53b to your computer and use it in GitHub Desktop.
Configure logback using pure Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.slf4j.LoggerFactory; | |
import ch.qos.logback.classic.Level; | |
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; | |
public class LogbackConfigureExample { | |
public static void main(String[] args) { | |
Logger foo = createLoggerFor("foo", "foo.log"); | |
Logger bar = createLoggerFor("bar", "bar.log"); | |
foo.info("test"); | |
bar.info("bar"); | |
} | |
private static Logger createLoggerFor(String string, String file) { | |
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); | |
PatternLayoutEncoder ple = new PatternLayoutEncoder(); | |
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n"); | |
ple.setContext(lc); | |
ple.start(); | |
FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>(); | |
fileAppender.setFile(file); | |
fileAppender.setEncoder(ple); | |
fileAppender.setContext(lc); | |
fileAppender.start(); | |
Logger logger = (Logger) LoggerFactory.getLogger(string); | |
logger.addAppender(fileAppender); | |
logger.setLevel(Level.DEBUG); | |
logger.setAdditive(false); /* set to true if root should log too */ | |
return logger; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment