2014-02-24 185 views
7

我想讓LogBack DBAppender從編程配置工作,但似乎無法使其運行。以編程方式配置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); 

任何想法什麼可能是錯的?我在控制檯中看到一個日誌,但沒有任何數據庫。一直與這一戰鬥,並會感謝任何見解!

+0

你已經在數據庫中設置一個'loggingConnectionInfo.getUri()'指向表? – Alden

+0

是,所有這一切都設置,並使用XML配置安裝時,一切工作正常。 – ebensing

回答

1

我相信@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); 
+0

我曾嘗試過,但它沒有奏效。我認爲主要的事情是與數據庫連接不好(整個mysql'%'不包括localhost,doh) – ebensing