我正在尝试使LogBack DBAppender通过编程配置工作,但似乎无法使其正常运行。

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
DBAppender dbAppender = new DBAppender();
dbAppender.setContext(lc);
DriverManagerConnectionSource connectionSource = new DriverManagerConnectionSource();
connectionSource.setDriverClass("com.mysql.jdbc.Driver");
connectionSource.setUrl(loggingConnectionInfo.getUri());
connectionSource.setUser(loggingConnectionInfo.getUser());
connectionSource.setPassword(loggingConnectionInfo.getPassword());
connectionSource.setContext(lc);
connectionSource.start();
dbAppender.setConnectionSource(connectionSource);
dbAppender.start();

logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.setLevel(Level.DEBUG);
logger.addAppender(dbAppender);

知道有什么问题吗?我在控制台中看到一条日志,但是数据库没有任何记录。经过一段时间的努力,不胜感激!

最佳答案

我相信@ebensing找到了问题,这是LoggerContext。这是一个工作版本,最大的区别是logger.getLoggerContext():

Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.setLevel(Level.DEBUG);

DriverManagerConnectionSource connSource = new DriverManagerConnectionSource();
connSource.setDataSource(ds);
connSource.setContext(logger.getLoggerContext());
connSource.start();

DBAppender dbAppender = new DBAppender();
dbAppender.setConnectionSource(connSource);
dbAppender.setContext(logger.getLoggerContext());
dbAppender.start();

logger.addAppender(dbAppender);

10-08 18:40