forked from kidgrow-microservices-platform

克 刘
2020-03-16 549148d90d41a3320bd36d469fd690354c78de58
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.kidgrow.zuul.service;
 
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import com.kidgrow.common.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: zuul代理后响应处理器<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/4 14:49 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
@Slf4j
@Component
public class AccessLogService {
    private ExecutorService executorService;
 
//    @Autowired
//    private AmqpTemplate amqpTemplate;
 
    @Value("${spring.application.name}")
    private String defaultServiceId;
 
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
 
    public AccessLogService() {
        Integer availableProcessors = Runtime.getRuntime().availableProcessors();
        Integer numOfThreads = availableProcessors * 2;
        executorService = new ThreadPoolExecutor(numOfThreads, numOfThreads, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
    }
 
    @JsonIgnore
    private Set<String> ignores = new HashSet<>(Arrays.asList(new String[]{
            "/**/oauth/check_token",
            "/**/gateway/access/logs",
            "/webjars/**"
    }));
 
    /**
     * 不记录日志
     *
     * @param requestPath
     * @return
     */
    public boolean ignore(String requestPath) {
        Iterator<String> iterator = ignores.iterator();
        while (iterator.hasNext()) {
            String path = iterator.next();
            if (antPathMatcher.match(path, requestPath)) {
                return true;
            }
        }
        return false;
    }
 
    public void sendLog(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        int httpStatus = response.getStatus();
        String requestPath = request.getRequestURI();
        String method = request.getMethod();
        Map headers = WebUtils.getHttpHeaders(request);
        Map data = WebUtils.getParameterMap(request);
        Object serviceId = request.getAttribute(FilterConstants.SERVICE_ID_KEY);
        String ip = WebUtils.getRemoteAddress(request);
        String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
        Object requestTime = request.getAttribute("requestTime");
        String error = null;
        if (ex != null) {
            error = ex.getMessage();
        }
        if (ignore(requestPath)) {
            return;
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put("requestTime", requestTime);
        map.put("serviceId", serviceId == null ? defaultServiceId : serviceId);
        map.put("httpStatus", httpStatus);
        map.put("headers", JSONObject.toJSON(headers));
        map.put("path", requestPath);
        map.put("params", JSONObject.toJSON(data));
        map.put("ip", ip);
        map.put("method", method);
        map.put("userAgent", userAgent);
        map.put("responseTime", new Date());
        map.put("error", error);
        //OpenUserDetails user = OpenHelper.getUser();
 
//        if (user != null) {
//            map.put("authentication", JSONObject.toJSONString(user));
//        }
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
//                    amqpTemplate.convertAndSend(QueueConstants.QUEUE_ACCESS_LOGS, map);
                    log.info(map.toString());
                } catch (Exception e) {
                    log.error("access logs save error:{}", e);
                }
            }
        });
    }
}