log4j 将日志记录到数据库

需要以下jar包:

---log4j

commons-loggin-1.1.1.jar

log4j-1.2.16.jar

---mysql

mysql-connector-java-5.1.15-bin.jar

 

---log4j.properties配置内容

log4j.rootLogger=INFO,DATABASE

#JDBC Appender

log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout

#与数据库建立连接   
log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test
log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
log4j.appender.DATABASE.user=root
log4j.appender.DATABASE.password=
log4j.appender.DATABASE.sql=insert into wlog(class_name,method_name,create_time,log_level,log_info,log_type) values(%C, %M, %d{yyyy-MM-dd HH:mm:ss}, %p, %m, %X{type})

---表结构

CREATE TABLE wlog (
  id INT NOT NULL AUTO_INCREMENT,
  class_name VARCHAR(100) NULL COMMENT 类名,
  method_name VARCHAR(100) NULL COMMENT 方法名,
  create_time VARCHAR(45) NULL COMMENT 产生时间,
  log_level VARCHAR(45) NULL COMMENT 日志级别,
  log_info VARCHAR(45) NULL COMMENT 日志信息,
  log_type INT NULL COMMENT 日志类别,
  PRIMARY KEY (id));

 

--Log4jtest.java

    private static final Logger lg = Logger.getLogger(Log4jtest.class);
   
    
    public static void main(String[] args) {
         MDC.put("type", "1");
         
        lg.error("Log4jtes错误信息");
        lg.warn("Log4jtest警告信息");
        lg.info("Log4jtest信息");
    }

--result

mysql> select * from wlog;
+----+------------------------+-------------+---------------------+-----------+-----------------------+----------+
| id | class_name             | method_name | create_time         | log_level | log_info              | log_type |
+----+------------------------+-------------+---------------------+-----------+-----------------------+----------+
|  1 | com.yan.test.Log4jtest | main        | 2014-06-19 15:25:04 | ERROR     | Log4jtes错误信息      |        1 |
|  2 | com.yan.test.Log4jtest | main        | 2014-06-19 15:25:04 | WARN      | Log4jtest警告信息     |        1 |
|  3 | com.yan.test.Log4jtest | main        | 2014-06-19 15:25:04 | INFO      | Log4jtest信息         |        1 |
+----+------------------------+-------------+---------------------+-----------+-----------------------+----------+
3 rows in set (0.00 sec)

 

 

log4j 将日志记录到数据库,布布扣,bubuko.com

log4j 将日志记录到数据库

上一篇:ubuntu下安装Apache+PHP+Mysql


下一篇:EXCEL页面数据快速写入SQL数据库