java-中记录⽤户操作⽇志(⽅法⼊参结果出参)本地打印⽅便
服务器中查看⽇志
1package com.property.framework.aspectj;
2
3import com.alibaba.fastjson.JSON;
4import com.fasterxml.jackson.databind.ObjectMapper;
5import com.propertymon.utils.ServletUtils;
slf4j.Slf4j;
7import org.apachemons.lang3.StringUtils;
8import org.aspectj.lang.JoinPoint;
9import org.aspectj.lang.Signature;
10import org.aspectj.lang.annotation.AfterReturning;
11import org.aspectj.lang.annotation.Aspect;
12import org.aspectj.lang.annotation.Before;
13import org.aspectj.lang.annotation.Pointcut;
14import org.springframework.http.ResponseEntity;
15import org.springframework.stereotype.Component;
16import org.t.request.RequestContextHolder;
17import org.t.request.ServletRequestAttributes;
18
write的返回值19import javax.servlet.http.HttpServletRequest;
20import java.util.Map;
21import java.util.StringJoiner;
22
23/**
24* @className: OperLogAspect
25* @program: property-new-admin
26* @description:
27* @author: wangliangzhi
28* @create: 2022-02-17 17:17
29*/
30@Aspect
31@Slf4j
32@Component
33public class OperLogAspect {
34/**
35* 开始时间
36*/
37private ThreadLocal<Long> startTime = new ThreadLocal<>();
38/**
39* ⽇志记录
40*/
41private ThreadLocal<String> logApi = new ThreadLocal<>();
42
43
44// "execution(public * com.property.*.controller.*..*.*(..))" 这⾥换成你的接⼝地址
45// 也就是随便⼀个 controller 复制他的地址就可以了
46@Pointcut("execution(public * com.property.*.controller.*..*.*(..))")
47private void pointcut() {
48
49}
50
51@Before("pointcut()")
52private void beforeExeApi(JoinPoint joinPoint) {
53ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestAttributes();
54if (servletRequestAttributes != null) {
55HttpServletRequest request = Request();
56startTime.set(System.currentTimeMillis());
57// ip
58String ip = getRemoteHost(request);
59// 请求⽅式
60String httpMethod = Method();
61// url附带的参数
62String urlParam = getUrlParam(request);
63// body 参数
64String bodyParam = "";
65if ("POST".equals(httpMethod)) {
66bodyParam = Args());
67}
68Signature signature = Signature();
69// ⽅法名
70String methodName = Name();
71// ⽬标类
72String targetClass = Target().getClass().getName();
73log.info("统⼀⽇志记录: 操作IP:[{}], 请求⽅式:[{}], 接⼝地址:[{}], 请求地址:[{}], get请求参数:[{}], post请求参数:[{}]",
74ip, httpMethod, targetClass, Request().getRequestURI(), urlParam, bodyParam);
75}
76}
77
78/**
78/**
79* @Description 切⼊点⽅法执⾏之后执⾏,@AfterReturning是在⼀个Join Point(连接点)正常返回后执⾏的Advice(增强)
80* @Version 1.0
81*/
82@AfterReturning(value = "pointcut()", returning = "returnValue")
83public void afterReturning(JoinPoint joinPoint, Object returnValue) {
84// ip
85String ip = Request());
86// ⽅法名
87String methodName = Request().getRequestURI();
88// ⽬标类
89String targetClass = Target().getClass().getName();
90try {
91String asString;
92long total = System.currentTimeMillis() - ();
93String logv = ();
94logv = StringUtils.join(logv, "统⼀⽇志记录:操作IP:[" + ip + "], 接⼝地址:[" + targetClass + "], 请求地址:[" + methodName + "],总耗时:" + total + "ms", "\n"); 95if (total < 5000L) {
96// 超过5秒数据量⼤没必要记录⽇志
97ObjectMapper objectMapper = new ObjectMapper();
98if (null == returnValue) {
99logv = StringUtils.join(logv, "返回结果:", "\n");
100} else if (returnValue instanceof ResponseEntity) {
101asString = objectMapper.writeValueAsString(((ResponseEntity) returnValue).getBody());
102
103logv = StringUtils.join(logv, "返回结果:" + (asString.length() > 5000 ? "数据量过⼤不打印结果" : asString), "\n");
104} else {
105asString = objectMapper.writeValueAsString(returnValue);
106logv = StringUtils.join(logv, "返回结果:" + (asString.length() > 5000 ? "数据量过⼤不打印结果" : asString), "\n");
107}
108} else {
109logv = StringUtils.join(logv, "耗时过长不打印结果");
110}
111logApi.set(logv);
112log.());
113} catch (Exception e) {
<(e.toString());
115} finally {
116// 释放资源
119}
120}
121
122
123private String getUrlParam(HttpServletRequest request) {
124Map<String, String[]> parameterMap = ParameterMap();
125StringBuilder paramKv = new StringBuilder();
126StringJoiner urlParam = new StringJoiner(", ");
127for (Map.Entry<String, String[]> entry : Set()) {
128for (String s : Value()) {
129paramKv.Key()).append("=").append(s);
130}
131urlParam.String());
132paramKv = new StringBuilder();
133}
String();
135}
136
137/**
138* 获取⽬标主机的ip
139*
140* @param request
141* @return
142*/
143private String getRemoteHost(HttpServletRequest request) {
144String ip = Header("x-forwarded-for");
145if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
146ip = Header("Proxy-Client-IP");
147}
148if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
149ip = Header("WL-Proxy-Client-IP");
150}
151if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
152ip = RemoteAddr();
153}
154return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
155}
156
157}
⽂中⽤到的 ServletUtils
1package com.propertymon.utils;
1package com.propertymon.utils;
2
3import stant.FileConstants;
4import ext.Convert;
5import org.t.request.RequestAttributes;
6import org.t.request.RequestContextHolder;
7import org.t.request.ServletRequestAttributes;
8
9import javax.servlet.http.HttpServletRequest;
10import javax.servlet.http.HttpServletResponse;
11import javax.servlet.http.HttpSession;
12import java.io.IOException;
13
14/**
15* 客户端⼯具类
16*
17* @author wangliangzhi
18*/
19public class ServletUtils {
20/**
21* 获取String参数
22*/
23public static String getParameter(String name) {
24return getRequest().getParameter(name);
25}
26
27/**
28* 获取String参数
29*/
30public static String getParameter(String name, String defaultValue) {
Str(getRequest().getParameter(name), defaultValue);
32}
33
34/**
35* 获取Integer参数
36*/
37public static Integer getParameterToInt(String name) {
Int(getRequest().getParameter(name));
39}
40
41/**
42* 获取Integer参数
43*/
44public static Integer getParameterToInt(String name, Integer defaultValue) { Int(getRequest().getParameter(name), defaultValue);
46}
47
48/**
49* 获取request
50*
51* @return
52*/
53public static HttpServletRequest getRequest() {
54return getRequestAttributes().getRequest();
55}
56
57/**
58* 获取response
59*/
60public static HttpServletResponse getResponse() {
61return getRequestAttributes().getResponse();
62}
63
64/**
65* 获取session
66*/
67public static HttpSession getSession() {
68return getRequest().getSession();
69}
70
71public static ServletRequestAttributes getRequestAttributes() {
72RequestAttributes attributes = RequestAttributes(); 73return (ServletRequestAttributes) attributes;
74}
75
76/**
77* 将字符串渲染到客户端
78*
79* @param response 渲染对象
80* @param string 待渲染的字符串
81* @return null
82*/
83public static String renderString(HttpServletResponse response, String string) { 84try {
85response.setStatus(200);
85response.setStatus(200);
86response.setContentType("application/json");
87response.setCharacterEncoding("utf-8");
89} catch (IOException e) {
90e.printStackTrace();
91}
92return null;
93}
94
95/**
96* 是否是Ajax异步请求
97*
98* @param request
99*/
100public static boolean isAjaxRequest(HttpServletRequest request) {
101String accept = Header("accept");
102if (accept != null && accept.indexOf("application/json") != -1) {
103return true;
104}
105
106String xRequestedWith = Header("X-Requested-With");
107if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
108return true;
109}
110
111String uri = RequestURI();
112if (StringUtils.inStringIgnoreCase(uri, FileConstants.JSON_SUFFIX, FileConstants.XML_SUFFIX)) {
113return true;
114}
115
116String ajax = Parameter("__ajax");
117if (StringUtils.inStringIgnoreCase(ajax, FileConstants.FILE_TYPE_JSON, FileConstants.FILE_TYPE_XML)) { 118return true;
119}
120return false;
121}
122}
123
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论