我有一个简单的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;。
什么是问题?
答案 0 :(得分:0)
如果您看到org.apache.log4j.jdbc.JDBCAppender
的{{3}},您会在方法setSql
中注意到需要org.apache.log4j.PatternLayout
的实例。所以你得到的错误是正确。
基本上,您有两种选择:
org.apache.log4j.PatternLayout
。org.apache.log4j.jdbc.JDBCAppender
并覆盖方法setSql
。将其添加到您的配置中。