采用切面的方式:
@Aspect
@Component
public class WebLogAspect {
private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
@Pointcut("execution(public * com.fbc..controller.*.*(..))")//兩個..代表所有子目錄,最后括號里的兩個..代表所有參數
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到請求,記錄請求內容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 記錄下請求內容
logger.info("請求地址 : " + request.getRequestURL().toString());
logger.info("HTTP METHOD : " + request.getMethod());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
logger.info("參數 : " + Arrays.toString(joinPoint.getArgs()));
// loggger.info("參數 : " + joinPoint.getArgs());
}
@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的參數名一致
public void doAfterReturning(Object ret) throws Throwable {
logger.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();// ob 為方法的返回值
logger.info("耗時 : " + (System.currentTimeMillis() - startTime));
return ob;
}
}