日志处理

    科技2022-07-16  115

    通过AOP来实现

    功能

    1.记录请求的url 2.记录访问者ip 3.记录调用方法的classMethod和参数args

    package com.hgmj.workblog.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; 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; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * Created by limi on 2017/10/13. */ @Aspect @Component public class LogAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Pointcut("execution(* com.hgmj.workblog.controller.*(..))")//定义一个切面 public void log() {} @Before("log()")//所有的controller下的方法在返回值前都会执行这个方法 public void doBefore(JoinPoint joinPoint) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest();//获取request请求 String url = request.getRequestURL().toString();//获取request请求路径 String ip = request.getRemoteAddr();//获取ip String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs();//获取请求的参数 RequestLog requestLog = new RequestLog(url, ip, classMethod, args); logger.info("Request : {}", requestLog); } @After("log()") public void doAfter() { // logger.info("--------doAfter--------"); } //AfterReturning:获取返回的结果;pointcut:切面 @AfterReturning(returning = "result",pointcut = "log()") public void doAfterRuturn(Object result) { logger.info("Result : {}", result); } private class RequestLog { private String url; private String ip; private String classMethod; private Object[] args; public RequestLog(String url, String ip, String classMethod, Object[] args) { 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) + '}'; } } }
    Processed: 0.010, SQL: 8