我在logback.xml中定义了一个logback附加程序,它是一个数据库附加程序,但是我很好奇是否有任何方法可以使用定义为bean的我自己的连接池在java中配置该附加程序。
我发现类似的事情,但没有实际答案。
这是一个对我有用的简单示例(请注意,在此示例中我使用FileAppender)
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 Loggerutils { 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; } }