Java 用于自定义字段的Apache log4 J DB配置
我有一个项目的要求,我们需要更新数据库的日志。 因此,我们对ApacheLog4J进行了如下配置Java 用于自定义字段的Apache log4 J DB配置,java,mysql,apache,Java,Mysql,Apache,我有一个项目的要求,我们需要更新数据库的日志。 因此,我们对ApacheLog4J进行了如下配置 # Define the root logger with appender file log4j.rootLogger = DEBUG, DB # Define the DB appender log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender # Set JDBC URL log4j.appender.DB.URL=jdbc:mysql:
# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB
# Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
# Set JDBC URL
log4j.appender.DB.URL=jdbc:mysql://localhost:3306/test
# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver
# Set database user name and password
log4j.appender.DB.user=root
log4j.appender.DB.password=
# Set the SQL statement to be executed.
log4j.appender.DB.sql=insert into coupon(couponId,customerName,date,level,message) values("%X{couponId}","%X{customerName}","%d","%p","%m")
# Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
由于我们需要在日志表中随日志一起更新几个自定义字段,所以我们调用了MDC,如下所示
但在此配置之后,insert语句由于以下异常而失败
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 'AS': initialization started')' at line 1
正如一些博客所建议的那样,我们添加了5.1.29版本的m-sql-connector.jar
我仍然得到错误
public class DBLoggerTest {
static Logger logger;
public DBLoggerTest() {
//System.setProperty("log4j.configuration", "log4j.properties");
logger = Logger.getLogger(DBLoggerTest.class.getName());
}
public static void main(String[] args) {
MDC.put("couponId",couponId);
MDC.put("customerName",customerName);
logger.error("customer logs in");
MDC.getContext().clear();
}
}
CREATE TABLE coupon
(
couponId varchar(25),
customerName varchar(25),
date Timestamp,
level varchar(10),
message varchar(2500),
);
请您为这个错误提出任何解决方案,并建议任何更新自定义字段和日志的指针
谢谢
Kana您在log4j.properties中对log4j.appender.DB.sql键的值字符串使用了双引号而不是单引号 您应该使用单引号来表示以下内容
log4j.appender.DB.sql=insert into coupon(couponId,customerName,date,level,message) values('%X{couponId}', '%X{customerName}', '%d', '%p', '%m')
在log4j.appender.DB.sql键的log4j.properties中,对值字符串使用了双引号而不是单引号 您应该使用单引号来表示以下内容
log4j.appender.DB.sql=insert into coupon(couponId,customerName,date,level,message) values('%X{couponId}', '%X{customerName}', '%d', '%p', '%m')