gongzuming
2024-08-23 129038de7ede53e626ef1bbc25623bc39c646fd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.mzl.flower.config;
 
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.utils.IpUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
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.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
 
 
@Aspect
@Component
public class LoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
 
    @Pointcut("execution(public * com.mzl.flower.web.*.*Controller.*(..))")
    public void controllerLoggingPointcut() {
    }
 
    @Before("controllerLoggingPointcut()")
    public void logBefore(JoinPoint joinPoint) {
    }
 
    @AfterReturning(pointcut = "controllerLoggingPointcut()", returning = "jsonResult")
    public void logAfter(Object jsonResult) {
 
    }
 
    @Around("controllerLoggingPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //程序开始的时间
        long beginTime = System.currentTimeMillis();
        String result = "success";
        String errorMsg = "";
        try {
            Object o = joinPoint.proceed();
            return o;
        } catch (Throwable e) {
            if(e instanceof ValidationException){
                result = "validate";
                errorMsg = ((ValidationException) e).getErrorMessageKey();
            }else{
                result = "error";
                final Writer writer = new StringWriter();
                final PrintWriter print = new PrintWriter(writer);
                e.printStackTrace(print);
                errorMsg = e.getMessage();
            }
            throw e;
        } finally {
            //程序结束的时间
            long endTime = System.currentTimeMillis();
            //程序运行结束的耗时
            long requestTime = endTime - beginTime;
 
            // 接收到请求
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String logReturnMsg = "{\"startTime\":\"{}\",\"endTime\":\"{}\",\"method\":\"{}\",\"api\":\"{}\"" +
                    ",\"ip\":\"{}\",\"duration\":\"{}\",\"result\":\"{}\",\"errorMsg\":\"{}\"}";
            if("success".equals(result) || "validate".equals(result)){
                logger.info(logReturnMsg, beginTime, endTime, request.getMethod(), request.getRequestURI(), IpUtil.getIpAddress(request), requestTime, result, errorMsg);
            }else{
                logger.error(logReturnMsg, beginTime, endTime, request.getMethod(), request.getRequestURI(), IpUtil.getIpAddress(request), requestTime, result, errorMsg);
            }
        }
    }
}