SpringBoot整合log4j2
<dependency> <!-- 引入log4j2依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
去除SpringBoot默认的logback配置:
可以使用IDEA中的Maven Helper 插件排除掉logback的配置:
编写log4j2配置文件,并在application配置中引用:
sql语句的显示需要用log4j的实现
<!-- 对应数据库表 -->
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="INFO" monitorInterval="5">
<appenders>
<JDBC name="databaseAppender" tableName="fc_log">
<ConnectionFactory class="com.xxxx.xxxx.ConnectionFactory" method="getDatabaseConnection"/>
<!-- pattern中填写标准的log4j2参数即可 %msg %d 等 -->
<Column name="log_user" pattern=""/>
<Column name="log_file" pattern=""/>
<Column name="log_line" pattern="%c"/>
<Column name="log_date" pattern="%d{yyyy-MM-dd hh:mm:ss}"/>
<Column name="log_message" pattern="%m"/>
</JDBC>
</appenders>
<loggers>
<logger name="com.xxxx" level="debug">
<AppenderRef ref="databaseAppender" level="debug" />
</logger>
</loggers>
</configuration>
编写数据库连接池(druid):
public class ConnectionFactory{
private DruidDataSource dataSource;
private static ConnectionFactory connectionFactory;
private Connection getConnection() throws SQLException {
Properties properties = new Properties();
String user = "数据库用户名";
String password = "数据库密码";
String url = "jdbc:mysql://localhost:3306/(数据库名称)?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf8";
String driverClassName = "com.mysql.cj.jdbc.Driver";
properties.put("driverClassName",driverClassName);
properties.put("url",url);
properties.put("username",user);
properties.put("password",password);
try {
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
try {
init();
} catch (Exception e2) {
}
}
return dataSource.getConnection();
}
public static Connection getDatabaseConnection() throws SQLException {
if(connectionFactory == null){
connectionFactory = new ConnectionFactory();
}
return connectionFactory.getConnection();
}
public void init(){
try {
if (dataSource != null)
dataSource.close();
} catch (Exception e) {
}
}
}
最后测试即可。
此方法存在一个待优化的点,在于数据库性能会受到影响,且影响较大,期待各位大神的优化