log4j JDBCAppender java.lang.ClassCastException

时间:2015-05-10 06:51:54

标签: java jdbc log4j

我有一个简单的log4j示例:

Test.java:

package com.mobin.pack1;

import org.apache.log4j.Logger;

public class Test {
    final static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {
         try {
         int x = 0;
            int y = 5;
            int z = y/x;

            System.out.println(z);

         } catch (Exception e) {
            logger.error("error" , e);
         }      
    }
}

log4j.properties:

log4j.rootLogger = DEBUG, DB
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:mysql://localhost/logDB
log4j.appender.DB.driver=com.mysql.jdbc.Driver
log4j.appender.DB.user=root
log4j.appender.DB.password=123
log4j.appender.DB.sql=INSERT INTO TestLOGS(DATE,LOGGER,LEVEL,MESSAGE,THROWABLE) VALUES('%d{yyyy-MM-dd HH:mm:ss}','%C:%L','%p','%m','%throwable{100}')
log4j.appender.DB.layout=org.apache.log4j.EnhancedPatternLayout

依赖性:

<dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
</dependency>

TestLOGS表:

CREATE TABLE IF NOT EXISTS `TestLOGS` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `DATE` varchar(20) COLLATE utf8_bin NOT NULL,
  `LOGGER` varchar(100) COLLATE utf8_bin NOT NULL,
  `LEVEL` varchar(10) COLLATE utf8_bin NOT NULL,
  `MESSAGE` varchar(1000) COLLATE utf8_bin NOT NULL,
  `THROWABLE` varchar(1000) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2 ;

当我运行它时,我得到了这样的例外:

log4j:WARN Failed to set property [sql] to value "INSERT INTO TestLOGS(DATE,LOGGER,LEVEL,MESSAGE,THROWABLE) VALUES('%d{yyyy-MM-dd HH:mm:ss}','%C:%L','%p','%m','%throwable{100}')". 
java.lang.reflect.InvocationTargetException
.
.
.
Caused by: java.lang.ClassCastException: org.apache.log4j.EnhancedPatternLayout cannot be cast to org.apache.log4j.PatternLayout at org.apache.log4j.jdbc.JDBCAppender.setSql(JDBCAppender.java:330)
.
.
.
log4j:ERROR Failed to excute sql
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'error' at line 1

但当我改变&#34; org.apache.log4j.EnhancedPatternLayout&#34; log4j.properties中的org.apache.log4j.PatternLayout我没有得到这些异常,但是在表格的THROWABLE列插入值&#34; mainhrowable {100}&#34;。

什么是问题?

1 个答案:

答案 0 :(得分:0)

如果您看到org.apache.log4j.jdbc.JDBCAppender的{​​{3}},您会在方法setSql中注意到需要org.apache.log4j.PatternLayout的实例。所以你得到的错误是正确

基本上,您有两种选择:

  • 修改您的SQL语句并使用org.apache.log4j.PatternLayout
  • 扩展班级org.apache.log4j.jdbc.JDBCAppender并覆盖方法setSql。将其添加到您的配置中。