Log4j之重写JDBCAppender
新建类:MyLoggingEvent , 来转换单引号
/**
*
*/
package com.hr.core;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;
/**
* @author zhong
*
*/
public class MyLoggingEvent extends LoggingEvent {
private static final long serialVersionUID = -1405129465403337629L;
public MyLoggingEvent(String fqnOfCategoryClass, Category logger, Priority level, Object message, Throwable throwable) {
super(fqnOfCategoryClass, logger, level, message, throwable);
// TODO Auto-generated constructor stub
}
public String getThreadName() {
// TODO Auto-generated method stub
String thrdName=super.getThreadName();
if(thrdName.indexOf("'")!=-1){
thrdName=thrdName.replaceAll("'", "''");
}
return thrdName;
}
public String getRenderedMessage() {
String msg=super.getRenderedMessage();
if(msg.indexOf("'")!=-1){
msg=msg.replaceAll("'", "''");
}
return msg;
}
}
新建类:MyJDBCAppender , 来解发重写方法的调用
/**
*
*/
package com.hr.core;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.LoggingEvent;
/**
* @author zhong
*
*/
public class MyJDBCAppender extends JDBCAppender {
protected String getLogStatement(LoggingEvent event) {
String fqnOfCategoryClass=event.fqnOfCategoryClass;
Category logger=Category.getRoot();
Priority level=event.level;
Object message=event.getMessage();
Throwable throwable=null;
MyLoggingEvent bEvent=new MyLoggingEvent(fqnOfCategoryClass,logger,level,message,throwable);
return super.getLogStatement(bEvent);
}
}
附: log4j.properties 配置
log4j.rootCategory=INFO,A3,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy MMM dd HH:mm:ss,SSS}%m%n
log4j.logger.Java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout,logfile,A3
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/hr_log.log
log4j.appender.R.MaxFileSize=1024KB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[HL] %p %t %c - %m%n
#
log4j.appender.A3=com.hr.core.MyJDBCAppender
log4j.appender.A3.URL=jdbc\:sqlserver\://localhost\:1433;DatabaseName\=zhaochi_1
log4j.appender.A3.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
log4j.appender.A3.user=sa
log4j.appender.A3.password=pwterp
#
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=INSERT INTO log4j(createDate,thread,grade,class,message) values('%d','%t','%-5p','%c','%m')