log4J2写入mysql

看这篇文章前可以先看下 http://blog.csdn.net/ererfei/article/details/50884155,我这只实验了mysql,其他没弄过


log4j2.xml配置

























ConnectionFactory.java

package com.session.test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;

public class ConnectionFactory {
private static interface Singleton {
final ConnectionFactory INSTANCE = new ConnectionFactory();
}

private final DataSource dataSource;

private ConnectionFactory() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(0);
}

Properties properties = new Properties();
properties.setProperty("user", "账号");
properties.setProperty("password", "密码");

GenericObjectPool pool = new GenericObjectPool();
DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
"jdbc:mysql://localhost:3306/数据库名字", properties);

new PoolableConnectionFactory(connectionFactory, pool, null, null, false, true);

this.dataSource = new PoolingDataSource(pool);
}

public static Connection getDatabaseConnection() throws SQLException {
return Singleton.INSTANCE.dataSource.getConnection();
}
}
数据库创表

  1. DROP TABLE IF EXISTS `ibs_log`;  
  2. CREATE TABLE `ibs_log` (  
  3.  `log_id` int(10) NOT NULL AUTO_INCREMENT,  
  4.  `log_date` datetime NOT NULL COMMENT '日期',  
  5.  `log_file` varchar(255) DEFAULT NULL COMMENT '文件名',  
  6.  `log_line` varchar(255) DEFAULT NULL COMMENT '行号',  
  7.   `log_thread`varchar(255) DEFAULT NULL COMMENT '线程',  
  8.  `log_level` varchar(255) DEFAULT NULL COMMENT 'Log级别 info warndebug error等',  
  9.  `log_message` varchar(2048) DEFAULT NULL COMMENT 'Log信息',  
  10.  PRIMARY KEY (`log_id`,`log_date`),  
  11.   KEY`INDEX_LOG_DATE` (`log_date`) USING BTREE  
  12. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
测试

  @Test
    public void test_select() {
          //这样自定义的错误就可以记录在表了,如果要系统详细信息,就修改下log4j2.xml的配置

          Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);  
   logger.error("自定义错误");  
     
    }
需要的包: 以下就列出了 log4j2 的包



org.apache.logging.log4j
log4j-api
2.5


org.apache.logging.log4j
log4j-core
2.5


 
   commons-dbcp
   commons-dbcp
   1.4


 

你可能感兴趣的:(日志)