Springboot项目实战(二):日志处理

日志处理

直接传送到目录网址,点我!!!!

1.请求URL
2.访问者ip
3.返回内容
4.参数args
5.调用方法classMethod

主要目的,记录访问者ip,URL,及其日志信息
在这里插入图片描述

1.@Pointcut(“execution()”)中匹配规则问题 springboot 项目

 @Pointcut("execution(* com.xyj.blog.web.*.*(..))")

2.LogAspect类(主要作用记录访问者ip,url)

package com.xyj.blog.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;

/**
 * @author xyj
 * @date 2020/4/4 -18:25
 */
@Aspect
@Component//开启主键扫描,为了可以扫描到这个类
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //定义一个切面
    @Pointcut("execution(* com.xyj.blog.web.*.*(..))")
    public void log() {
    }


    @Before("log()")//通过joinpoint获取
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        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() {

    }

    @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) +
                    '}';
        }
    }
}

3.启动后可以在日志中记录
在这里插入图片描述

发布了9 篇原创文章 · 获赞 42 · 访问量 5630

猜你喜欢

转载自blog.csdn.net/weixin_44625302/article/details/105324431