依赖:(应该是不用那么多jar包的)
log4j
log4j
1.2.16
org.slf4j
jcl-over-slf4j
xxx
org.slf4j
slf4j-log4j12
1.7.0
org.slf4j
slf4j-api
1.7.0
org.springframework
spring-aop
xxxx
org.aspectj
aspectjrt
1.7.4
org.aspectj
aspectjweaver
1.7.4
在springmvc.xml中配置
id="logPointCutAll"/>
pointcut-ref="logPointCut"
arg-names="joinPoint,retValue"
returning="retValue"
method="afterReturning"
/>
pointcut-ref="logPointCutAll"
throwing="e" />
切面类
package com.huawei.log;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Component
public class LogInterceptor {
private final Logger logger = Logger.getLogger(LogInterceptor.class);
private long startTimeMillis = 0; // 开始时间
private long endTimeMillis = 0; // 结束时间
private HttpServletRequest request = null;
private SimpleDateFormat format = new SimpleDateFormat("yyyy--MM-dd hh:mm:ss");
public void before(JoinPoint joinPoint){
Object object[] = joinPoint.getArgs(); // 获取被切函数 的参数
request = getHttpServletRequest();
}
/**
* 后置通知 【即 被切函数执行完之后 执行该 函数】
* @param joinPoint
* @param retValue 被切函数的返回值
*/
public void afterReturning(
JoinPoint joinPoint,Object retValue){
//Object object[] = joinPoint.getArgs(); // 获取被切函数 的参数
logger.info("------返回数据:"+retValue);
logger.info( "------请求结束时间:"+format.format(System.currentTimeMillis()));
logger.info("请求end!======================");
}
public void after(){
}
public void afterThrowing(
Throwable e){
logger.error("afterThrowing: "+e.getMessage(), e);
}
/**
* @Description: 获取request
* @param
* @return HttpServletRequest
*/
public HttpServletRequest getHttpServletRequest(){
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes)ra;
HttpServletRequest request = sra.getRequest();
return request;
}
}