SpringBoot配置log4j2的JdbcAppender日誌寫入資料庫,可定義哪些日誌寫入
阿新 • • 發佈:2019-01-04
MarkerFilter用來定義寫入日誌到資料庫的標記過濾器,只有使用了該標記的log才寫入到資料庫(後面有程式碼) ColumnConfig.createColumnConfig的第二個引數為資料庫欄位名,ID為自動增長可以不在這定義 logs是你定義的表名 注意:Connect不要自己new Connect(),new出來的不能將日誌寫入資料庫 3、定義一個Marker標記類import javax.annotation.PostConstruct; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.db.jdbc.ColumnConfig; import org.apache.logging.log4j.core.appender.db.jdbc.JdbcAppender; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.filter.MarkerFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class LogAppender { @Autowired private Connect connect; @PostConstruct public void init(){ final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final Logger interLogger = ctx.getLogger("com.hhaip"); //需要寫日誌到資料庫的包名 ColumnConfig[] cc = { ColumnConfig.createColumnConfig(config, "CLASS", "%C", null, null, "false", null), ColumnConfig.createColumnConfig(config, "FUNCTION", "%M", null, null, "false", null), ColumnConfig.createColumnConfig(config, "LEVEL", "%level", null, null, "false", null), ColumnConfig.createColumnConfig(config, "LOGGER", "%logger", null, null, "false", null), ColumnConfig.createColumnConfig(config, "MESSAGE", "%message", null, null, "false", null), ColumnConfig.createColumnConfig(config, "LOG_DATE", null, null, "true", null, null) } ; //配置Marker過濾器(標記過濾器) MarkerFilter filter = MarkerFilter.createFilter("dblog", Filter.Result.ACCEPT, Filter.Result.DENY); Appender appender = JdbcAppender.createAppender("databaseAppender", "true", filter, connect, "0", "logs", cc); config.addAppender(appender); interLogger.addAppender(appender); appender.start(); ctx.updateLoggers(); } }
4、在方法中呼叫日誌列印,自定義哪些日誌寫入資料庫 log.info("helloworld"); //不會被寫入資料庫import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class Markers { public static final Marker DB = MarkerFactory.getMarker("dblog"); //dblog就是上面MarkerFilter裡的標記 }
log.info(Markers.DB, "查詢所有的售貨機,數量為:{}", pageVo.getTotal()); //使用了Maeker標記,這條日誌會被寫入資料庫