当前位置: 代码迷 >> Web前端 >> 关于log4j在SSH中输出日记的配置
  详细解决方案

关于log4j在SSH中输出日记的配置

热度:242   发布时间:2012-08-30 09:55:54.0
关于log4j在SSH中输出日志的配置
 

(一).首先配置好SSH jar包

(二).在web.xml中配置监听器:

 <!-- 加载log4j配置文件 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:config/log/log4j_config.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

?(三).定义日志log4j_config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "file:///D:\soft\log4j\log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="dailyFile" class="org.apache.log4j.DailyRollingFileAppender">
	<param name="File" value="c:\\logs\\log.log"/>
	<param name="Append" value="true"/>
	<param name="Encoding" value="UTF-8"/>
	<layout class="org.apache.log4j.PatternLayout">
		<param name="ConversionPattern" value="%-6p%d{yyyy-MM-dd HH:mm}[%t]-%m%n"/>
	</layout>
</appender>
 <logger name="org.springframework">
	<level value="INFO"/>
	<appender-ref ref="dailyFile"/>
</logger>
<logger name="org.hibernate">
	<level value="INFO"/>
	<appender-ref ref="dailyFile"/>
</logger>
<logger name="org.apache">
	<level value="INFO"/>
	<appender-ref ref="dailyFile"/>
</logger>
<logger name="com.opensymphony">
	<level value="INFO"/>
	<appender-ref ref="dailyFile"/>
</logger> 
<logger name="com.mchange">
	<level value="INFO"/>
	<appender-ref ref="dailyFile"/>
</logger> 
<root>
	<priority value="INFO"/>
	<appender-ref ref="dailyFile"/>
</root>
</log4j:configuration>

?(四).日志输出到C:\logs\log.log文件中

?(五).有可能加载log4j.dtd文件

?(六).配置logAdvice.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	   http://www.springframework.org/schema/tx http://www.springframework.org/tx/spring-tx-3.0.xsd
	   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
		
	   <bean id="logAfter" class="com.newsicom.jxc.common.aop.log.LogAfterAdvice"	/>
	   <bean id="logBefore" class="com.newsicom.jxc.common.aop.log.LogBeforeAdvice" />
	   <bean id="logThrow" class="com.newsicom.jxc.common.aop.log.LogThrowAdvice" />
	   
	   <aop:config>
	   			<aop:pointcut id="serviceOperation-logAfter" expression="execution(* com.newsicom.jxc.basicinfo.goodsunits.service..*.*(..))" />
	   			<aop:advisor pointcut-ref="serviceOperation-logAfter" advice-ref="logAfter" />
	   </aop:config>
	
	   <aop:config>
	           <aop:pointcut id="serviceOperation-logBefore" expression="execution(* com.newsicom.jxc.basicinfo.goodsunits.service..*.*(..))"/>
		       <aop:advisor pointcut-ref="serviceOperation-logBefore" advice-ref="logBefore"  /> 
	   </aop:config>
	
	   <aop:config>
		      	<aop:pointcut id="serviceOperation-logThrow" expression="execution(* com.newsicom.jxc.basicinfo.goodsunits.service..*.*(..))"/>
				<aop:advisor pointcut-ref="serviceOperation-logThrow" advice-ref="logThrow"  /> 
	   </aop:config> 	   
</beans>

?(七).编写Advice:

 LogAfterAdvice
/**
 * LogAfterAdvice
 */
package com.newsicom.jxc.common.aop.log;

import java.lang.reflect.Method;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;

public class LogAfterAdvice implements AfterReturningAdvice{

	private static final Logger log=Logger.getLogger(LogAfterAdvice.class);

	
	public void afterReturning(Object returnValue, Method method, Object[] args,
			Object target) throws Throwable {
		log.log(Level.INFO, target.getClass().getName()+"调用"+method.getName()+"结束,返回值:"+returnValue+"---");
	}
}

?? LogBeforeAdvice:

package com.newsicom.jxc.common.aop.log;

import java.lang.reflect.Method;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;

public class LogBeforeAdvice implements MethodBeforeAdvice {

	private static final Logger log=Logger.getLogger(LogBeforeAdvice.class);
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		log.log(Level.INFO, target.getClass().getName()+"调用"+method.getName()+"开始---");
	}
}

?LogThrowAdvice:

?

package com.newsicom.jxc.common.aop.log;
import java.lang.reflect.Method;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.aop.ThrowsAdvice;

import com.newsicom.jxc.common.util.GeneralUtil;
/**
 * @author 
 * 
 */
public class LogThrowAdvice implements ThrowsAdvice {

	private static final Logger log = Logger.getLogger(LogThrowAdvice.class);

	public void afterThrowing(Method method, Object[] args, Object target,
			Throwable throwable) {
		log.log(Level.ERROR,
				target.getClass().getName() + "调用" + method.getName()
						+ "时有异常抛出:" + GeneralUtil.getTrace(throwable) + "---");
	}
}

?(八).在applicationContext.xml中添加logAdvice.xml

<!-- Aop日志追踪 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />
	<import resource="classpath:config/log/logAdvice.xml" /> 

  

? (九).辅助类:

package com.newsicom.jxc.common.constant;
public final class CommonConstant {

	public final static String EMPTY_STRING = "";
}
?
/*
 * @(#)GeneralUtil.java  1.0.0 2011/06/15
 * 
 * Copyright 2011 uniebiz.com. All rights reserved.
 * UNIEBIZ PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.newsicom.jxc.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringEscapeUtils;

import com.newsicom.jxc.common.constant.CommonConstant;
import com.opensymphony.xwork2.ActionContext;

public class GeneralUtil {
	public static final String createGuid() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}

	public static final boolean strIsNullOrEmpty(String str) {
		boolean isNullOrEmpty = (str == null || str
				.equals(CommonConstant.EMPTY_STRING));
		return isNullOrEmpty;
	}

	
	public static final String getCookieByName(HttpServletRequest request,
			String name) {
		String returnvalue = null;
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					returnvalue = cookie.getValue();
					break;
				}
			}
		}
		return returnvalue;
	}

	
	public static final String dateFormat(String format, Date date) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	
	public static final String HTMLEncode(String str) {
		return StringEscapeUtils.escapeHtml(str);
	}

	
	public static final String HTMLDecode(String str) {
		return StringEscapeUtils.unescapeHtml(str);
	}

	
	public static String[] getDateStr(Calendar calendar) {

		
		String tem[] = new String[5];
		
		int mondayValue = calendar.get(Calendar.MONDAY) + 1;
		String month = "0" + mondayValue;
		tem[0] = calendar.get(Calendar.YEAR)
				+ month.substring(month.length() - 2);

		// 遍历四次 获得本月前四个月的字符串
		for (int i = 1; i < 5; i++) {
			calendar.add(Calendar.MONTH, -1);
			mondayValue = calendar.get(Calendar.MONDAY) + 1;
			month = "0" + mondayValue;
			tem[i] = calendar.get(Calendar.YEAR)
					+ month.substring(month.length() - 2);//
		}

		return tem;
	}

	/**
	 * 
	 * 方法名:<code>getBetweenDate</code></br> 功能描述??根据给定的Calendar
	 * 			获得当前日期??个月前的1????0??0??0的日期放到日期数组中
	 * 
	 * @param calendar
	 *            给定的Calender
	 * @return 日期 Date数组
	 */
	public static Date[] getBetweenDate(Calendar calendar) {

		Date[] dateTem = new Date[2];
		dateTem[0] = calendar.getTime();

		calendar.add(Calendar.MONTH, -4);
		calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);

		dateTem[1] = calendar.getTime();

		return dateTem;
	}
	
	/**
	 * 
	 * 方法名:<code>getCycleDate</code></br>
	 * 功能描述:消费周??
	 *      
	 *         
	 * @return 消费周期
	 */
	public static String getCycleDate() {
		String strDate="";
		
		Calendar  calendar = Calendar.getInstance();
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
		strDate =sdf.format(calendar.getTime());
		calendar.set(Calendar.DAY_OF_MONTH,1);
		strDate  =sdf.format(calendar.getTime()) + " ~ " + strDate;
		
		return strDate;
	}
 
	/**
	 * 
	 * 方法名:<code>setLocaleLanguage</code></br>
	 * 功能描述??
	 *     设置国际化语??
	 *         
	 * @param ac
	 * @param type
	 */
	public static void setLocaleLanguage(ActionContext ac, String type) {
		Locale l = Locale.getDefault();

		// 中文
		if ("zh_CN".equals(type)) {
			l = Locale.CHINESE;
		} else if ("en_US".equals(type)) {
			// 英文
			l = Locale.US;
		}

		// 设置语言
		ac.setLocale(l);
	}
	
	/**
	 * 
	 * 方法名:<code>getTrace</code></br>
	 * 功能描述??
	 *     获取异常堆栈信息??
	 *         
	 * @param t 抛出的异常??
	 * @return 异常堆栈字符串??
	 */
	public static String getTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter writer = new PrintWriter(sw);
		t.printStackTrace(writer);
		StringBuffer buffer = sw.getBuffer();
		return buffer.toString();
	}

}

?

?

?