【log4j2】LOG4J2保存至数据库的操作

SpringBoot整合log4j2

 
    org.springframework.boot
    spring-boot-starter-log4j2
 

去除SpringBoot默认的logback配置:


引用log4j2并排除logback

可以使用IDEA中的Maven Helper 插件排除掉logback的配置:


Maven Helper

编写log4j2配置文件,并在application配置中引用:

sql语句的显示需要用log4j的实现


application配置



    
      
          
          
          
          
          
          
          
      
  
  
      
          
      
  

编写数据库连接池(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) {
        }
    }
}

最后测试即可。

此方法存在一个待优化的点,在于数据库性能会受到影响,且影响较大,期待各位大神的优化

你可能感兴趣的:(【log4j2】LOG4J2保存至数据库的操作)