log4j JDBCAppender 消息中有单引号 BUG

洪光霁
2023-12-01

用log4j的JDBCAppender  输出到数据库如果 消息中有单引号,就会报SQLException。

解决办法就是重写JDBCAppender

1.新建类MyLoggingEvent

package com.ikuboo.custom;

import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;

/**
 * @ClassName:MyLoggingEvent.java
 * @Description:重写,替换message 单引号为 转义符
 * @author:Yuan
 * @version:V1.0
 * @Date:2016年6月7日 上午10:51:38
 */

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);
	}
	@Override
	public String getThreadName()
	{
		String thrdName = super.getThreadName();
		if (thrdName.indexOf("'") != -1)
		{
			thrdName = thrdName.replaceAll("'", "''");
		}
		return thrdName;
	}
	@Override
	public String getRenderedMessage()
	{
		String msg = super.getRenderedMessage();
		if (msg.indexOf("'") != -1)
		{
			msg = msg.replaceAll("'", "''");
		}
		return msg;
	}

}

2.新建类MyJDBCAppender

 

package com.ikuboo.custom;

import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;

/**
 * @ClassName:MyLoggingEvent.java
 * @Description:重写,替换message 单引号为 转义符
 * @author:Yuan
 * @version:V1.0
 * @Date:2016年6月7日 上午10:51:38
 */

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);
	}
	@Override
	public String getThreadName()
	{
		String thrdName = super.getThreadName();
		if (thrdName.indexOf("'") != -1)
		{
			thrdName = thrdName.replaceAll("'", "''");
		}
		return thrdName;
	}
	@Override
	public String getRenderedMessage()
	{
		String msg = super.getRenderedMessage();
		if (msg.indexOf("'") != -1)
		{
			msg = msg.replaceAll("'", "''");
		}
		return msg;
	}

}

 

 

 

 

 

3.修改log4j.properties

            log4j.appender.db=com.ikuboo.custom.MyJDBCAppender

 

 

 

 类似资料: