SpringBoot配置log4j2的JdbcAppender日志写入数据库,可定义哪些日志写入

  • 通过java代码给log4j2配置JdbcAppender,为什么不通过log4j2.xml配置,因为数据源的初始化在log4j2.xml后面,会导致初始化log4j2.xml初始化失败,数据源为空报空指针异常。
注意:@SLF4J是lombok.jar的注解,且使用lombok时需要下载lombok的eclipse插件并安装(官网有介绍)官网: https://projectlombok.org/

1、定义一张存储日志的表
CREATE TABLE logs (
		  ID INT(11) NOT NULL AUTO_INCREMENT,
		  CLASS VARCHAR(100) DEFAULT NULL,
		  FUNCTION VARCHAR(100) DEFAULT NULL,
		  LEVEL VARCHAR(100) DEFAULT NULL,
		  LOGGER VARCHAR(100) DEFAULT NULL,
		  MESSAGE TEXT,
		  LOG_DATE TIMESTAMP NULL DEFAULT NULL,
		  PRIMARY KEY (ID)
		) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
2、定义一个获取数据库连接的bean
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.logging.log4j.core.appender.db.jdbc.ConnectionSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Connect implements ConnectionSource {

	@Autowired
	private DataSource mysqlDataSource;
	
	@Override
	public Connection getConnection() throws SQLException {
		log.info("获取一个数据库连接");
		return mysqlDataSource.getConnection();
	}
}
mysqlDataSource是一个数据源,在其他地方定义了,你可以将你定义的数据库在此注入
2、定义一个类用来重写log4j2.xml对象
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();    
	}
}
 MarkerFilter用来定义写入日志到数据库的标记过滤器,只有使用了该标记的log才写入到数据库(后面有代码)
 ColumnConfig.createColumnConfig的第二个参数为数据库字段名,ID为自动增长可以不在这定义
 logs是你定义的表名
注意:Connect不要自己new Connect(),new出来的不能将日志写入数据库
3、定义一个Marker标记类
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

public class Markers {

	public static final Marker DB = MarkerFactory.getMarker("dblog");  //dblog就是上面MarkerFilter里的标记

}
4、在方法中调用日志打印,自定义哪些日志写入数据库
log.info("helloworld");   //不会被写入数据库
log.info(Markers.DB, "查询所有的售货机,数量为:{}", pageVo.getTotal()); //使用了Maeker标记,这条日志会被写入数据库


你可能感兴趣的:(Spring框架技术,SpringBoot)