使用log4j将log写入mysql

时间:2021-11-22 21:51:51

使用log4j将log写入mysql

在log4j 1.2.8 的api中JDBCAppender类的说明中有一段红字
WARNING: This version of JDBCAppender is very likely to be
  completely replaced in the future. Moreoever, it does
  not log exceptions.
1. 在mysql中创建库logdb
 create database;
2. 在库logdb中创建表muglog,
 create table muglog{
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    logdate DATE,
  logger VARCHAR(50),
    priority VARCHAR(50),
  message VARCHAR(255)
 };
3. 修改log4j.properties
 ### 限制com.bob.digester(名:dig)才会log on JDBCAppender ###
 log4j.logger.com.bob.digester=info, dig
 
 log4j.appender.dig=org.apache.log4j.jdbc.JDBCAppender
 log4j.appender.dig.URL=jdbc:mysql://localhost/logdb
 log4j.appender.dig.driver=com.mysql.jdbc.Driver
 log4j.appender.dig.user=root
 log4j.appender.dig.password=
 log4j.appender.dig.sql=INSERT INTO MUGLOG (LOGDATE, LOGGER, PRIORITY, MESSAGE) VALUES ('%d', '%c', '%p', '%m')
 log4j.appender.dig.layout=org.apache.log4j.PatternLayout
 
4. 注意,这里mysql的driver是mysql-connector-java-3.0.14-production-bin.jar里的com.mysql.jdbc.Driver
   所以,把它放到classpath里, 如在Eclipse测试,需放到project的java build path的Libraries里