扩展log4j,通过配置实现将业务日志记录到数据库中

扩展:
1. 扩展JDBCAppender
   在append方法中仅对扩展的日志对象做处理
2. 扩展PatternLayout
   支持JSTL的ExpressionEvaluator
3. 扩展Filter
   支持按class name做过滤

使用步骤:
1. 在log4j.xml中定义Appender
<appender name="jdbcChannelLog"
		class="com.xxx.wap.log.JDBCAppender">
		<param name="driver" value="com.mysql.jdbc.Driver" />
		<param name="URL" value="jdbc:mysql://localhost:3306/test" />
		<param name="user" value="admin" />
                  <param name="password" value="123" />
		<param name="bufferSize" value="1" />
		<layout class="com.xxx.wap.log.PatternLayout">
			<param name="ConversionPattern"
				value="insert into xx_channel_log(chanid,subid,request_timemillis,request_url,request_ip,session_id,service_id,path_id,resource_id,resource_file_id,type,misc_mid,misc_session_id,misc_service_id) values (''{chanid}'',''{subid}'',''{requestTimeMillis,date,yyyy-MM-dd HH:mm:ss}'',''{requestUrl}'',''{fromIp}'',''{sessionId}'',{serviceId,number,00000000},{pathId,number,00000000},{resourceId,number,00000000},{resourceFileId,number,00000000},{type},''{mid}'',''{miscSessionId}'',''{miscServiceId}'')" />
		</layout>
		<filter class="com.xxx.wap.log.LogObjectFilter">
			<param name="className" value="com.xxx.wap.log.item.EtChannelLog"/>		</filter>
	</appender>

2. 在log4j.xml中将定义的Appender添加到root里
<root>
		<priority value="warn" />
		<appender-ref ref="stdout" />
		<!--<appender-ref ref="file"/>-->
		<appender-ref ref="jdbcChannelLog" />
	</root>

3. 在相应的位置调用logger的方法(info,error等等)
EtChannelLog channelLog = new EtChannelLog();
		channelLog.setType(type);
		channelLog.setChanid(chanId);
		channelLog.setFromIp(request.getRemoteAddr());
		String subid = request.getParameter("subid");
		if (subid != null && subid.trim().length() > 0
				&& (!subid.trim().equalsIgnoreCase("null")))
			channelLog.setSubid(request.getParameter("subid"));
		channelLog.setRequestTimeMillis(System.currentTimeMillis());
		channelLog.setSessionId((request.getSession() == null) ? null : request
				.getSession().getId());
		String msisdn = HandsetUtil.getUserMobileNum(request);
		String mid = HandsetUtil.getUserMobileMid(request);
		channelLog.setMid(mid);
		channelLog.setMsisdn(msisdn);
		channelLog.setPathId(pathID);
		channelLog.setServiceId(serviceID);
		channelLog.setResourceId(resourceId);
		channelLog.setResourceFileId(resourceFileID);
		// ��url
		String url = request.getRequestURL().toString();
		if (request.getQueryString() != null)
			url += "?" + request.getQueryString();
		channelLog.setRequestUrl(url);
		channelLog.setMid(HandsetUtil.getUserMobileMid(request));
		channelLog.setMiscSessionId(request.getParameter("MISC_SessionID"));
		channelLog.setMiscServiceId(request.getParameter("MISC_ServiceID"));
		log.info(channelLog);

你可能感兴趣的:(log4j,xml)