2.4 日志处理
2.4.1 记录日志内容
- 请求url
- 访问者ip
- 调用方法classMethod
- 参数args
- 返回内容
2.4.2 新建包aspect,新建日志切面处理类
package com.fei.aspect;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* Created by zxf on 2019年9月28日
*/
@Aspect // 进行切面操作
@Component // 组件扫描
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
// 切面
@Pointcut("execution(* com.fei.controller.*.*(..))")
public void log() {
}
// 切面前操作
@Before("log()") // 传递切面方法
public void doBefore(JoinPoint joinPoint) {
logger.info("---------doBefore------");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String url = request.getRequestURL().toString();
String ip = request.getRemoteAddr();
Signature signature = joinPoint.getSignature();
String classMethod = signature.getDeclaringTypeName() + "." + signature.getName();
Object[] args = joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
logger.info("Reqeust : {}", requestLog);
}
// 切面后操作
@After("log()") // 传递切面方法
public void doAfter() {
logger.info("---------doAfter------");
}
// 切面返回后操作
@AfterReturning(returning = "result", pointcut = "log()") // 传递切面方法
public void doAfterReturn(Object result) {
logger.info("Result : {}", result);
}
/**
* 封装日志记录需要的内容
*
* @author fei
*
*/
private class RequestLog {
private String url;// 请求url
private String ip;// 访问者ip
private String classMethod;// 调用方法
private Object[] args;// 参数
public RequestLog(String url, String ip, String classMethod, Object[] args) {
super();
this.url = url;
this.ip = ip;
this.classMethod = classMethod;
this.args = args;
}
@Override
public String toString() {
return "[url=" + url + ", ip=" + ip + ", classMethod=" + classMethod + ", args=" + Arrays.toString(args)
+ "]";
}
}// RequestLog
}// LogAspect
测试日志切面处理Controller
@Controller
public class IndexController {
@GetMapping("/{id}/{name}")
public String toIndex(@PathVariable("id") Integer id, @PathVariable("name") String name) {
System.out.println("====index()方法执行====");
return "index";
}
}