├── LICENSE
├── README.md
├── pom.xml
└── src
└── main
├── java
└── com
│ └── github
│ ├── AopLog.java
│ ├── AopLogAutoConfiguration.java
│ ├── AopLogConfig.java
│ ├── AopLogProcessor.java
│ ├── Collector.java
│ ├── CollectorExecutor.java
│ ├── DataExtractor.java
│ ├── LogData.java
│ ├── LogDataAspect.java
│ ├── MessageFormatter.java
│ ├── SpringElSupporter.java
│ └── collector
│ ├── LogCollector.java
│ └── NothingCollector.java
└── resources
└── META-INF
└── spring.factories
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | AopLog
2 | ==================
3 |
4 | #### AopLog是基于SpringAop和ThreadLocal实现的一个对请求方法埋点信息收集与处理的日志工具包。
5 |
6 | 
7 | 
8 | 
9 | 
10 |
11 | 设计目的和场景 :
12 |
13 | - 使用Spring AOP拦截方法参数大部分做法基本上大同小异,不用每个项目工程都写AOP拦截处理日志的代码,引入此包即可。
14 | - 可获取埋点方法的请求参数,响应参数,请求头,以及内部耗时,方法是成功还是失败,自定义步骤记录等等信息。
15 | - 整个方法完整过程只产生一个埋点信息记录(一个LogData对象),比如`@Controller`中一次完整的http请求。
16 | - 收集情况可选,可只在异常时执行收集过程(有些只是为了排查问题打印的日志,程序正常运行时其实毫无意义)。
17 | - 埋点信息收集,自行实现收集过程,比如埋点日志打印,常见埋点日志写入数据库,写入到文件,写入队列等等。
18 | - 埋点信息收集不干扰埋点方法正常流程,收集过程异步化处理(默认,可通过注解的`asyncMode`进行设置),不影响正常请求方法的性能与响应。
19 | - 只需通过`@AopLog`注解(或者自定义切面)决定是否埋点收集。
20 |
21 | ### 快速开始
22 |
23 | #### 项目通过[Maven仓库地址](https://mvnrepository.com/artifact/com.github.ealenxie/aop-log/2.5) 的pom.xml引入。
24 |
25 | ```xml
26 |
27 |
28 | com.github.ealenxie
29 | aop-log
30 | 2.5
31 |
32 |
33 | ```
34 |
35 | #### 或者通过gradle引入
36 |
37 | ```gradle
38 | compile group: 'com.github.ealenxie', name: 'aop-log', version: '2.5'
39 | ```
40 |
41 | #### @AopLog注解使用,进行埋点收集
42 |
43 | 直接在类(作用类的所有方法)或类方法(作用于方法)上加上注解`@AopLog`,进行埋点收集
44 |
45 | 例如 :
46 |
47 | ```java
48 |
49 | @AopLog(type = "测试接口", stackTraceOnErr = true)
50 | @RestController
51 | public class AppController {
52 |
53 | @GetMapping("/app/sayHello")
54 | public RespBody sayHello() {
55 | return RespBody.ok("hello EalenXie");
56 | }
57 |
58 | }
59 |
60 | ```
61 |
62 | #### 自定义全局的日志收集器实现收集 LogCollector
63 |
64 | 例如只是简单打印,或写入到库等等。(例子只是提供参考说明,收集过程请不要完全照搬,没有考虑到LogData不能被序列化的情况)
65 |
66 | ```java
67 |
68 | import com.fasterxml.jackson.core.JsonProcessingException;
69 | import com.fasterxml.jackson.databind.ObjectMapper;
70 | import com.github.LogData;
71 | import com.github.collector.LogCollector;
72 | import lombok.extern.slf4j.Slf4j;
73 | import org.springframework.stereotype.Component;
74 |
75 | /**
76 | * @author EalenXie create on 2020/9/15 13:46
77 | * 此为样例参考
78 | * 配置一个简单的日志收集器 这里只是做了一个log.info打印一下,可以在这里写入到数据库中或者写入
79 | */
80 | @Slf4j
81 | @Component
82 | public class AopLogCollector implements LogCollector {
83 | private ObjectMapper objectMapper = new ObjectMapper();
84 |
85 | @Override
86 | public void collect(LogData logData) {
87 | try {
88 | log.info(objectMapper.writeValueAsString(logData));
89 | } catch (JsonProcessingException e) {
90 | e.printStackTrace();
91 | }
92 | }
93 | }
94 | ```
95 |
96 | 配置`@Component`的全局日志收集器只能配置一个。
97 |
98 | 接口调用 `/say/hello` 测试即可看看到控制台打印出结果 :
99 |
100 | ```
101 | 2020-09-16 16:01:04.782 INFO 2012 --- [AsyncExecutor-2] name.ealen.infra.advice.AopLogCollector : {"appName":"app-template","host":"127.0.0.1","port":8080,"clientIp":"192.168.110.1","reqUrl":"http://localhost:8080/app/sayHello","httpMethod":"GET","headers":{"User-Agent":"Apache-HttpClient/4.5.10 (Java/11.0.5)"},"type":"测试","content":"","method":"name.ealen.api.facade.AppController#sayHello","args":null,"respBody":{"code":"200","desc":"OK","message":"请求成功","dateTime":"2020-09-16 16:01:04","body":"hello EalenXie"},"logDate":1600243264780,"costTime":1,"threadName":"http-nio-8080-exec-3","threadId":33,"success":true}
102 | ```
103 |
104 | #### 埋点日志对象LogData属性说明
105 |
106 | **LogData 埋点日志对象获取的内容**
107 |
108 | | 字段 | 类型 | 注释 |
109 | |:-----------|:--------|:------------------------------------------|
110 | | appName | String | 应用名称 |
111 | | host | String | 主机 |
112 | | port | int | 端口号 |
113 | | clientIp | String | 请求客户端的Ip |
114 | | reqUrl | String | 请求地址 |
115 | | headers | Object | 请求头部信息(可选择获取) 默认获取user-agent,content-type |
116 | | tag | String | 操作标签,默认值undefined |
117 | | content | String | 方法步骤内容,默认是空,可使用LogData.step进行内容步骤记录 |
118 | | method | String | 请求的本地java方法 |
119 | | args | Object | 方法请求参数 |
120 | | respBody | Object | 方法响应参数 |
121 | | costTime | long | 整个方法内部耗时 |
122 | | logDate | Date | Log产生时间,LogData对象初始化的时间 |
123 | | threadName | String | 线程名称 |
124 | | threadId | long | 线程Id |
125 | | success | boolean | 执行状态,成功(true)/异常(false) |
126 |
127 | #### AopLog 注解选项说明
128 |
129 | | 选项 | 类型 | 说明 | 默认 |
130 | |:----------------|:------------------------------|:---------------------------------------|-------------------------------|
131 | | logOnErr | boolean | 仅当发生异常时才收集 | false |
132 | | tag | String | 操作标签 | 默认值"undefined" |
133 | | headers | String[] | 获取的header信息 ,选择要获取哪些header信息 | 默认"User-Agent","content-type" |
134 | | args | boolean | 是否获取请求参数 | true |
135 | | respBody | boolean | 是否获取响应参数 | true |
136 | | stackTraceOnErr | boolean | 当目标方法发生异常时,是否追加异常堆栈信息到LogData的content中 | false |
137 | | asyncMode | boolean | 异步方式收集 | true |
138 | | collector | Class extends LogCollector> | 指定日志收集器 | 默认不调整收集器,使用全局的日志收集器 |
139 |
140 | #### LogData的step方法。
141 |
142 | 记录步骤。(如果某些重要步骤希望被记录下来)
143 | 例如 :
144 |
145 | ```java
146 |
147 | import com.github.AopLog;
148 | import com.github.LogData;
149 | import name.ealen.infra.base.resp.RespBody;
150 | import org.springframework.web.bind.annotation.GetMapping;
151 | import org.springframework.web.bind.annotation.RestController;
152 |
153 |
154 | /**
155 | * @author EalenXie create on 2020/6/22 14:28
156 | */
157 | @AopLog(tag = "测试", stackTraceOnErr = true)
158 | @RestController
159 | public class AppController {
160 |
161 |
162 | @GetMapping("/app/sayHello")
163 | public RespBody sayHello() {
164 | LogData.step("1. 第一步执行完成");
165 | //......
166 | LogData.step("2. 第二步执行完成");
167 | //.....
168 | LogData.step("3. service的方法执行完成");
169 | //.....
170 | return RespBody.ok("hello EalenXie");
171 | }
172 |
173 | }
174 |
175 | ```
176 |
177 | 此时再次接口调用 `/say/hello` 测试即可看看到控制台打印出结果,重点观察content字段 :
178 |
179 | ```
180 | 2020-09-16 17:26:20.285 INFO 3284 --- [AsyncExecutor-2] name.ealen.infra.advice.AopLogCollector : {"appName":"app-template","host":"127.0.0.1","port":8080,"clientIp":"192.168.110.1","reqUrl":"http://localhost:8080/app/sayHello","httpMethod":"GET","headers":{"User-Agent":"Apache-HttpClient/4.5.10 (Java/11.0.5)"},"tag":"测试","content":"1. 第一步执行完成\n2. 第二步执行完成\n3. service的方法执行完成\n","method":"name.ealen.api.facade.AppController#sayHello","args":null,"respBody":{"code":"200","desc":"OK","message":"请求成功","dateTime":"2020-09-16 17:26:20","body":"hello EalenXie"},"logDate":1600248380283,"costTime":1,"threadName":"http-nio-8080-exec-2","threadId":32,"success":true}
181 | ```
182 |
183 | ```
184 | "content":"1. 第一步执行完成\n2. 第二步执行完成\n3. service的方法执行完成\n"
185 | ```
186 |
187 | #### 不通过@AopLog注解,通过自定义切面进行收集
188 |
189 | 自定义切面注入`AopLogProcessor`,调用`proceed(config, point)`即可
190 |
191 | ```java
192 |
193 |
194 | import com.github.AopLogConfig;
195 | import com.github.AopLogProcessor;
196 | import org.aspectj.lang.ProceedingJoinPoint;
197 | import org.aspectj.lang.annotation.Around;
198 | import org.aspectj.lang.annotation.Aspect;
199 | import org.aspectj.lang.annotation.Pointcut;
200 | import org.springframework.stereotype.Component;
201 |
202 | import javax.annotation.Resource;
203 |
204 | /**
205 | * Created by EalenXie on 2021/7/14 10:29
206 | * 自定义切面
207 | */
208 | @Aspect
209 | @Component
210 | public class CustomLogDataAspect {
211 |
212 | @Resource
213 | private AopLogProcessor aopLogProcessor;
214 | private static final AopLogConfig CONFIG;
215 |
216 | static {
217 | CONFIG = new AopLogConfig();
218 | CONFIG.setTag("操作标签");
219 | CONFIG.setStackTraceOnErr(false);
220 | CONFIG.setHeaders(new String[]{"content-type", "user-agent"});
221 | }
222 |
223 | // 自定义切点 execution(public * com.test.web.TestController.*(..))
224 | @Pointcut("execution(public * com.test.web.TestController.*(..))")
225 | public void test() {
226 | //ig
227 | }
228 |
229 | // 请使用环绕通知 @Around()
230 | @Around("test()")
231 | public Object note(ProceedingJoinPoint point) throws Throwable {
232 | return aopLogProcessor.proceed(CONFIG, point);
233 | }
234 | }
235 |
236 | ```
237 |
238 | #### Change Notes:
239 |
240 | 有关更改的详细信息,请参阅[发布说明](https://github.com/EalenXie/aop-log/releases)。
241 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 | com.github.ealenxie
7 | aop-log
8 | jar
9 | 2.5
10 | aop-log
11 | A logging collection tool based on Spring AOP and ThreadLocal implementations
12 | https://github.com/EalenXie/aop-log
13 |
14 |
15 | The Apache Software License, Version 2.0
16 | https://www.apache.org/licenses/LICENSE-2.0.txt
17 | repo
18 |
19 |
20 |
21 |
22 | EalenXie
23 | ealenxie@qq.com
24 | https://github.com/EalenXie
25 |
26 |
27 |
28 | https://github.com/EalenXie/aop-log
29 | https://github.com/EalenXie/aop-log.git
30 | https://github.com/EalenXie
31 |
32 |
33 | 2.6.2
34 | 1.9.7
35 | UTF-8
36 |
37 |
38 |
39 | org.springframework.boot
40 | spring-boot-starter-web
41 | ${spring-boot-starter-web.version}
42 |
43 |
44 | org.aspectj
45 | aspectjweaver
46 | ${aspectjweaver.version}
47 |
48 |
49 |
50 |
51 | snapshots
52 | https://oss.sonatype.org/content/repositories/snapshots
53 |
54 |
55 | snapshots
56 | https://oss.sonatype.org/service/local/staging/deploy/maven2
57 |
58 |
59 |
60 |
61 |
62 |
63 | org.apache.maven.plugins
64 | maven-compiler-plugin
65 | 3.1
66 |
67 | 8
68 | 8
69 | utf-8
70 |
71 |
72 |
73 | maven-deploy-plugin
74 | 2.8.2
75 |
76 |
77 | default-deploy
78 | deploy
79 |
80 | deploy
81 |
82 |
83 |
84 |
85 |
86 | org.sonatype.plugins
87 | nexus-staging-maven-plugin
88 | 1.6.7
89 | true
90 |
91 | snapshots
92 | https://oss.sonatype.org/
93 | true
94 |
95 |
96 |
97 | org.apache.maven.plugins
98 | maven-source-plugin
99 | 3.1.0
100 |
101 |
102 | attach-sources
103 |
104 | jar-no-fork
105 |
106 |
107 |
108 |
109 |
110 | org.apache.maven.plugins
111 | maven-javadoc-plugin
112 | 2.10.3
113 |
114 |
115 | attach-javadocs
116 |
117 | jar
118 |
119 |
120 |
121 |
122 |
123 |
124 | org.apache.maven.plugins
125 | maven-gpg-plugin
126 | 1.6
127 |
128 |
129 | sign-artifacts
130 | install
131 |
132 | sign
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
--------------------------------------------------------------------------------
/src/main/java/com/github/AopLog.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 |
4 | import com.github.collector.LogCollector;
5 | import com.github.collector.NothingCollector;
6 | import org.springframework.http.HttpHeaders;
7 |
8 | import java.lang.annotation.ElementType;
9 | import java.lang.annotation.Retention;
10 | import java.lang.annotation.RetentionPolicy;
11 | import java.lang.annotation.Target;
12 |
13 | /**
14 | * @author EalenXie Created on 2020/1/2 17:49.
15 | * AopLog Annotation
16 | */
17 | @Target({ElementType.METHOD, ElementType.TYPE})
18 | @Retention(RetentionPolicy.RUNTIME)
19 | public @interface AopLog {
20 |
21 | /**
22 | * 仅当发生异常时才记录
23 | *
24 | * @return Only record when an exception occurs
25 | */
26 | boolean logOnErr() default false;
27 |
28 | /**
29 | * 操作标签(操作分类)
30 | *
31 | * @return Operating the tag
32 | */
33 | String tag() default "undefined";
34 |
35 | /**
36 | * 记录的headers ,默认记录 content-type user-agent
37 | *
38 | * @return Headers for recording, default record content-type user-Agent
39 | */
40 | String[] headers() default {HttpHeaders.USER_AGENT, HttpHeaders.CONTENT_TYPE};
41 |
42 | /**
43 | * 切面是否记录 请求参数
44 | *
45 | * @return Whether the AOP records the request parameters
46 | */
47 | boolean args() default true;
48 |
49 | /**
50 | * 切面是否记录 响应参数
51 | *
52 | * @return Whether the AOP records the response parameters
53 | */
54 | boolean respBody() default true;
55 |
56 | /**
57 | * 当发生异常时,AOP是否追加异常堆栈信息到content
58 | *
59 | * @return When an exception occurs, does the slice append the exception stack information to content
60 | */
61 | boolean stackTraceOnErr() default false;
62 |
63 | /**
64 | * 异步模式 收集日志
65 | *
66 | * @return Asynchronous mode collects logs
67 | */
68 | boolean asyncMode() default true;
69 |
70 | /**
71 | * 指定专门的收集器
72 | *
73 | * @return Specify a specialized collector
74 | */
75 | Class extends LogCollector> collector() default NothingCollector.class;
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/github/AopLogAutoConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import com.github.collector.LogCollector;
4 | import com.github.collector.NothingCollector;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.ComponentScan;
10 | import org.springframework.context.annotation.Configuration;
11 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
12 |
13 | import java.util.concurrent.Executor;
14 |
15 | /**
16 | * @author EalenXie create on 2021/1/4 11:19
17 | */
18 | @ComponentScan
19 | @Configuration
20 | public class AopLogAutoConfiguration {
21 |
22 | private static final Logger log = LoggerFactory.getLogger(AopLogAutoConfiguration.class);
23 |
24 | /**
25 | * 默认配置一个空的收集器
26 | *
27 | * @return By default, an empty collector is configured
28 | */
29 | @Bean
30 | @ConditionalOnMissingBean(value = LogCollector.class)
31 | public LogCollector nothingCollector() {
32 | return new NothingCollector();
33 | }
34 |
35 |
36 | /**
37 | * 默认配置异步收集器线程池
38 | *
39 | * @return The asynchronous collector thread pool is configured by default
40 | */
41 | @Bean
42 | @ConditionalOnMissingBean(name = "collectorAsyncExecutor")
43 | public Executor collectorAsyncExecutor() {
44 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
45 | executor.setCorePoolSize(5);
46 | executor.setMaxPoolSize(10);
47 | executor.setQueueCapacity(256);
48 | executor.setThreadNamePrefix("collectorAsyncExecutor-");
49 | executor.setRejectedExecutionHandler((r, exec) -> log.error("collectorAsyncExecutor thread queue is full,activeCount:{},Subsequent collection tasks will be rejected,please check your LogCollector or config your Executor", exec.getActiveCount()));
50 | executor.initialize();
51 | return executor;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/github/AopLogConfig.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import com.github.collector.LogCollector;
4 | import com.github.collector.NothingCollector;
5 | import org.springframework.http.HttpHeaders;
6 |
7 | /**
8 | * Created by EalenXie on 2021/7/14 11:48
9 | */
10 | public class AopLogConfig {
11 | /**
12 | * 仅当发生异常时才记录
13 | */
14 | private boolean logOnErr;
15 | /**
16 | * 操作标签(操作分类)
17 | */
18 | private String tag;
19 | /**
20 | * 记录的headers ,默认记录 content-type user-agent
21 | */
22 | private String[] headers;
23 | /**
24 | * 切面是否记录 请求参数
25 | */
26 | private boolean args;
27 | /**
28 | * 切面是否记录 响应参数
29 | */
30 | private boolean respBody;
31 | /**
32 | * 当发生异常时,AOP是否追加异常堆栈信息到content
33 | */
34 | private boolean stackTraceOnErr;
35 | /**
36 | * 异步模式 收集日志
37 | */
38 | private boolean asyncMode;
39 | /**
40 | * 指定专门的收集器
41 | */
42 | private Class extends LogCollector> collector;
43 |
44 | public AopLogConfig() {
45 | this.logOnErr = false;
46 | this.tag = "undefined";
47 | this.headers = new String[]{HttpHeaders.USER_AGENT, HttpHeaders.CONTENT_TYPE};
48 | this.args = true;
49 | this.respBody = true;
50 | this.stackTraceOnErr = true;
51 | this.asyncMode = true;
52 | this.collector = NothingCollector.class;
53 | }
54 |
55 | public boolean isLogOnErr() {
56 | return logOnErr;
57 | }
58 |
59 | public void setLogOnErr(boolean logOnErr) {
60 | this.logOnErr = logOnErr;
61 | }
62 |
63 | public String getTag() {
64 | return tag;
65 | }
66 |
67 | public void setTag(String tag) {
68 | this.tag = tag;
69 | }
70 |
71 | public String[] getHeaders() {
72 | return headers;
73 | }
74 |
75 | public void setHeaders(String[] headers) {
76 | this.headers = headers;
77 | }
78 |
79 | public boolean isArgs() {
80 | return args;
81 | }
82 |
83 | public void setArgs(boolean args) {
84 | this.args = args;
85 | }
86 |
87 | public boolean isRespBody() {
88 | return respBody;
89 | }
90 |
91 | public void setRespBody(boolean respBody) {
92 | this.respBody = respBody;
93 | }
94 |
95 | public boolean isStackTraceOnErr() {
96 | return stackTraceOnErr;
97 | }
98 |
99 | public void setStackTraceOnErr(boolean stackTraceOnErr) {
100 | this.stackTraceOnErr = stackTraceOnErr;
101 | }
102 |
103 | public boolean isAsyncMode() {
104 | return asyncMode;
105 | }
106 |
107 | public void setAsyncMode(boolean asyncMode) {
108 | this.asyncMode = asyncMode;
109 | }
110 |
111 | public Class extends LogCollector> getCollector() {
112 | return collector;
113 | }
114 |
115 | public void setCollector(Class extends LogCollector> collector) {
116 | this.collector = collector;
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/src/main/java/com/github/AopLogProcessor.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import com.github.collector.LogCollector;
4 | import com.github.collector.NothingCollector;
5 | import org.aspectj.lang.ProceedingJoinPoint;
6 | import org.aspectj.lang.reflect.MethodSignature;
7 | import org.springframework.beans.BeanUtils;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.context.ApplicationContext;
10 | import org.springframework.core.env.Environment;
11 | import org.springframework.stereotype.Component;
12 |
13 | import java.io.PrintWriter;
14 | import java.io.StringWriter;
15 | import java.util.HashMap;
16 | import java.util.Map;
17 |
18 | /**
19 | * @author EalenXie create on 2020/6/28 15:07
20 | * AopLog 切面处理器
21 | * LogData Aspect Processor
22 | */
23 | @Component
24 | public class AopLogProcessor {
25 |
26 | private final ApplicationContext applicationContext;
27 | private final CollectorExecutor collectorExecutor;
28 | private final LogCollector logCollector;
29 | private final SpringElSupporter elSupporter = new SpringElSupporter();
30 | private final Map, LogCollector> collectors = new HashMap<>();
31 | private final String appName;
32 |
33 |
34 | public AopLogProcessor(@Autowired ApplicationContext applicationContext,
35 | @Autowired CollectorExecutor collectorExecutor,
36 | @Autowired LogCollector logCollector) {
37 | this.applicationContext = applicationContext;
38 | this.collectorExecutor = collectorExecutor;
39 | this.logCollector = logCollector;
40 | this.appName = getAppName(applicationContext);
41 | }
42 |
43 | public String getAppName(ApplicationContext applicationContext) {
44 | Environment environment = applicationContext.getEnvironment();
45 | String name = environment.getProperty("spring.application.name");
46 | if (name != null) {
47 | return name;
48 | }
49 | if (applicationContext.getId() != null) {
50 | return applicationContext.getId();
51 | }
52 | StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
53 | for (StackTraceElement stackTraceElement : stackTrace) {
54 | if ("main".equals(stackTraceElement.getMethodName())) {
55 | return stackTraceElement.getFileName();
56 | }
57 | }
58 | return applicationContext.getApplicationName();
59 | }
60 |
61 | public String getAppName() {
62 | return appName;
63 | }
64 |
65 | /**
66 | * 处理 日志数据切面
67 | *
68 | * @param config AopLog 配置
69 | * @param point 切入point对象
70 | * @return 返回执行结果
71 | * @throws Throwable Exceptions in AOP should be thrown out and left to the specific business to handle
72 | */
73 | public Object proceed(AopLogConfig config, ProceedingJoinPoint point) throws Throwable {
74 | try {
75 | LogData.removeCurrent();
76 | LogData data = LogData.getCurrent();
77 | return proceed(config, data, point);
78 | } finally {
79 | LogData.removeCurrent();
80 | }
81 | }
82 |
83 | /**
84 | * 选择一个收集器进行执行
85 | */
86 | private LogCollector selectLogCollector(Class extends LogCollector> clz) {
87 | if (clz == NothingCollector.class || clz == null) {
88 | return logCollector;
89 | } else {
90 | LogCollector collector;
91 | try {
92 | collector = applicationContext.getBean(clz);
93 | } catch (Exception e) {
94 | collector = collectors.get(clz);
95 | if (collector == null) {
96 | collector = BeanUtils.instantiateClass(clz);
97 | collectors.put(clz, collector);
98 | }
99 | }
100 | return collector;
101 | }
102 | }
103 |
104 |
105 | /**
106 | * 方法执行处理记录
107 | *
108 | * @param aopLog 注解对象
109 | * @param data 日志数据
110 | * @param point 切入point对象
111 | * @return 返回执行结果
112 | * @throws Throwable Exceptions in AOP should be thrown out and left to the specific business to handle
113 | */
114 | private Object proceed(AopLogConfig aopLog, LogData data, ProceedingJoinPoint point) throws Throwable {
115 | Object result = null;
116 | boolean success = false;
117 | try {
118 | result = point.proceed();
119 | success = true;
120 | return result;
121 | } catch (Throwable throwable) {
122 | if (aopLog.isStackTraceOnErr()) {
123 | try (StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw, true)) {
124 | throwable.printStackTrace(writer);
125 | LogData.step("Fail : \n" + sw);
126 | }
127 | }
128 | throw throwable;
129 | } finally {
130 | if (!aopLog.isLogOnErr() || !data.isSuccess()) {
131 | data.setAppName(appName);
132 | data.setCostTime(System.currentTimeMillis() - data.getLogDate().getTime());
133 | MethodSignature signature = (MethodSignature) point.getSignature();
134 | data.setTag(elSupporter.getByExpression(signature.getMethod(), point.getTarget(), point.getArgs(), aopLog.getTag()).toString());
135 | data.setMethod(signature.getDeclaringTypeName() + "#" + signature.getName());
136 | DataExtractor.logHttpRequest(data, aopLog.getHeaders());
137 | if (aopLog.isArgs()) {
138 | data.setArgs(DataExtractor.getArgs(signature.getParameterNames(), point.getArgs()));
139 | }
140 | if (aopLog.isRespBody()) {
141 | data.setRespBody(DataExtractor.getResult(result));
142 | }
143 | data.setSuccess(success);
144 | LogData.setCurrent(data);
145 | if (aopLog.isAsyncMode()) {
146 | collectorExecutor.asyncExecute(selectLogCollector(aopLog.getCollector()), LogData.getCurrent());
147 | } else {
148 | collectorExecutor.execute(selectLogCollector(aopLog.getCollector()), LogData.getCurrent());
149 | }
150 | }
151 | }
152 | }
153 |
154 | }
155 |
--------------------------------------------------------------------------------
/src/main/java/com/github/Collector.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 |
4 | /**
5 | * @author EalenXie create on 2021/1/4 16:51
6 | * 收集器
7 | */
8 | @FunctionalInterface
9 | public interface Collector {
10 |
11 | /**
12 | * 收集数据对象
13 | *
14 | * @param data 数据对象
15 | */
16 | void collect(T data);
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/github/CollectorExecutor.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import org.springframework.scheduling.annotation.Async;
4 | import org.springframework.scheduling.annotation.EnableAsync;
5 | import org.springframework.stereotype.Component;
6 |
7 | /**
8 | * @author EalenXie on 2021/4/20 9:23
9 | * 执行器 使用收集器执行收集过程
10 | */
11 | @Component
12 | @EnableAsync(proxyTargetClass = true)
13 | public class CollectorExecutor {
14 |
15 | /**
16 | * 异步 执行收集器
17 | *
18 | * @param collector 收集器
19 | * @param data 数据对象
20 | */
21 | @Async("collectorAsyncExecutor")
22 | public void asyncExecute(Collector collector, D data) {
23 | execute(collector, data);
24 | }
25 |
26 | /**
27 | * 同步 执行收集器
28 | *
29 | * @param collector 收集器
30 | * @param data 数据对象
31 | */
32 | public void execute(Collector collector, D data) {
33 | collector.collect(data);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/github/DataExtractor.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.http.MediaType;
6 | import org.springframework.web.context.request.RequestContextHolder;
7 | import org.springframework.web.context.request.ServletRequestAttributes;
8 |
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 | import javax.xml.bind.JAXBContext;
12 | import javax.xml.bind.JAXBException;
13 | import javax.xml.bind.Marshaller;
14 | import java.io.IOException;
15 | import java.io.StringWriter;
16 | import java.util.HashMap;
17 | import java.util.Map;
18 |
19 | /**
20 | * @author EalenXie create on 2020/8/28 13:36
21 | * Data Extractor 数据抽取器
22 | */
23 | public class DataExtractor {
24 |
25 | private static final Logger log = LoggerFactory.getLogger(DataExtractor.class);
26 | private static final String AND_REG = "&";
27 | private static final String EQUALS_REG = "=";
28 | private static final Map, Marshaller> marshallerMap = new HashMap<>();
29 |
30 | private DataExtractor() {
31 |
32 | }
33 |
34 | /**
35 | * 获取HttpServletRequest对象
36 | *
37 | * @return HttpServletRequest
38 | */
39 | public static HttpServletRequest getRequest() {
40 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
41 | return attributes != null ? attributes.getRequest() : null;
42 | }
43 |
44 | /**
45 | * 获取HttpServletResponse对象
46 | *
47 | * @return HttpServletResponse
48 | */
49 | public static HttpServletResponse getResponse() {
50 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
51 | return attributes != null ? attributes.getResponse() : null;
52 | }
53 |
54 | /**
55 | * 获取请求参数内容
56 | *
57 | * @param parameterNames 参数名称列表
58 | * @param args 参数列表
59 | * @return Gets the request parameter content
60 | */
61 | public static Object getArgs(String[] parameterNames, Object[] args) {
62 | Object target;
63 | if (args.length == 1) {
64 | target = args[0];
65 | } else {
66 | target = args;
67 | }
68 | if (target == null) {
69 | return null;
70 | }
71 | HttpServletRequest request = getRequest();
72 | if (request != null && request.getContentType() != null) {
73 | String contentType = request.getContentType();
74 | if (MediaType.APPLICATION_XML_VALUE.equals(contentType)) {
75 | return xmlArgs(target);
76 | }
77 | if (MediaType.APPLICATION_JSON_VALUE.equals(contentType)) {
78 | return target;
79 | }
80 | }
81 | return appletArgs(parameterNames, args);
82 | }
83 |
84 |
85 | /**
86 | * 获取程序执行结果内容
87 | *
88 | * @param resp 响应对象
89 | * @return Gets the contents of the program execution results
90 | */
91 | public static Object getResult(Object resp) {
92 | if (resp == null) {
93 | return null;
94 | }
95 | HttpServletResponse response = getResponse();
96 | if (response != null && MediaType.APPLICATION_XML_VALUE.equals(response.getContentType())) {
97 | return xmlArgs(resp);
98 | } else {
99 | return resp;
100 | }
101 | }
102 |
103 | /**
104 | * 获取程序参数
105 | *
106 | * @param parameterNames 参数名
107 | * @param args 参数值
108 | * @return Get program parameters
109 | */
110 | public static Object appletArgs(String[] parameterNames, Object[] args) {
111 | if (parameterNames == null || parameterNames.length == 0 || args == null || args.length == 0) {
112 | return null;
113 | }
114 | StringBuilder sb = new StringBuilder();
115 | for (int i = 0; i < parameterNames.length; i++) {
116 | String parameterValue = "";
117 | if (args[i] != null) {
118 | parameterValue = args[i].toString();
119 | }
120 | sb.append(parameterNames[i]).append(EQUALS_REG).append(parameterValue).append(AND_REG);
121 | }
122 | if (sb.lastIndexOf(AND_REG) != -1) {
123 | sb.deleteCharAt(sb.lastIndexOf(AND_REG));
124 | }
125 | return sb.toString();
126 | }
127 |
128 |
129 | /**
130 | * 解析XML 数据
131 | *
132 | * @param pointArgs 切点参数
133 | * @return Parsing XML data
134 | */
135 | public static Object xmlArgs(Object pointArgs) {
136 | try (StringWriter writer = new StringWriter()) {
137 | Marshaller marshaller = getMarshaller(pointArgs.getClass());
138 | if (marshaller != null) {
139 | marshaller.marshal(pointArgs, writer);
140 | return writer.toString().replace("standalone=\"yes\"", "");
141 | }
142 | } catch (JAXBException e) {
143 | log.warn("parse xml data exception", e.getLinkedException());
144 | } catch (IOException e) {
145 | log.warn("writer close exception", e);
146 | }
147 | return pointArgs;
148 | }
149 |
150 | private static Marshaller getMarshaller(Class> clz) throws JAXBException {
151 | if (marshallerMap.containsKey(clz)) {
152 | return marshallerMap.get(clz);
153 | } else {
154 | Marshaller marshaller = JAXBContext.newInstance(clz).createMarshaller();
155 | marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
156 | marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
157 | marshallerMap.put(clz, marshaller);
158 | return marshaller;
159 | }
160 | }
161 |
162 |
163 | /**
164 | * 抽取 HttpServletRequest 对象信息
165 | *
166 | * @param data logData Object
167 | * @param headers headers
168 | */
169 | public static void logHttpRequest(LogData data, String[] headers) {
170 | HttpServletRequest request = getRequest();
171 | if (request != null) {
172 | data.setHost(request.getLocalAddr());
173 | data.setPort(request.getLocalPort());
174 | data.setClientIp(request.getRemoteAddr());
175 | data.setReqUrl(request.getRequestURL().toString());
176 | data.setHttpMethod(request.getMethod());
177 | Map headersMap = new HashMap<>(8);
178 | for (String header : headers) {
179 | if (header != null && header.trim().length() > 0) {
180 | headersMap.put(header, request.getHeader(header));
181 | }
182 | }
183 | data.setHeaders(headersMap);
184 | }
185 | }
186 |
187 | }
188 |
--------------------------------------------------------------------------------
/src/main/java/com/github/LogData.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 |
4 | import java.util.Date;
5 |
6 | /**
7 | * @author EalenXie Created on 2019/12/23 16:46.
8 | * Log data object (no external constructor is provided; there is only one such object per thread)
9 | * 自定义日志数据对象 (不提供对外的构造方法,每个线程中仅有一个此对象)
10 | */
11 | public class LogData {
12 |
13 | private LogData() {
14 | }
15 |
16 | /**
17 | * 线程LogData对象
18 | */
19 | private static final ThreadLocal LOG_DATA = new ThreadLocal<>();
20 | /**
21 | * 线程StringBuilder对象 主要用于追加字段到最终的content
22 | */
23 | private static final ThreadLocal CONTENT_BUILDER = new ThreadLocal<>();
24 | /**
25 | * 应用名
26 | */
27 | private String appName;
28 | /**
29 | * 主机
30 | */
31 | private String host;
32 | /**
33 | * 端口号
34 | */
35 | private Integer port;
36 | /**
37 | * 请求Ip
38 | */
39 | private String clientIp;
40 | /**
41 | * 请求地址
42 | */
43 | private String reqUrl;
44 | /**
45 | * http请求method
46 | */
47 | private String httpMethod;
48 | /**
49 | * 请求头部信息(可选择记录)
50 | */
51 | private Object headers;
52 | /**
53 | * 操作标签
54 | */
55 | private String tag;
56 | /**
57 | * 方法内容
58 | */
59 | private String content;
60 | /**
61 | * 操作方法
62 | */
63 | private String method;
64 | /**
65 | * 参数
66 | */
67 | private Object args;
68 | /**
69 | * 响应体
70 | */
71 | private Object respBody;
72 | /**
73 | * 操作日期(调用日期)
74 | */
75 | private Date logDate;
76 | /**
77 | * 业务处理耗时
78 | */
79 | private long costTime;
80 | /**
81 | * 线程名
82 | */
83 | private String threadName = Thread.currentThread().getName();
84 | /**
85 | * 线程Id
86 | */
87 | private long threadId = Thread.currentThread().getId();
88 | /**
89 | * 执行状态 成功(true)/异常(false) 默认失败false
90 | */
91 | private boolean success = false;
92 |
93 | public String getAppName() {
94 | return appName;
95 | }
96 |
97 | public void setAppName(String appName) {
98 | this.appName = appName;
99 | }
100 |
101 | public String getHost() {
102 | return host;
103 | }
104 |
105 | public void setHost(String host) {
106 | this.host = host;
107 | }
108 |
109 | public Integer getPort() {
110 | return port;
111 | }
112 |
113 | public void setPort(Integer port) {
114 | this.port = port;
115 | }
116 |
117 | public String getClientIp() {
118 | return clientIp;
119 | }
120 |
121 | public void setClientIp(String clientIp) {
122 | this.clientIp = clientIp;
123 | }
124 |
125 | public String getReqUrl() {
126 | return reqUrl;
127 | }
128 |
129 | public void setReqUrl(String reqUrl) {
130 | this.reqUrl = reqUrl;
131 | }
132 |
133 | public String getHttpMethod() {
134 | return httpMethod;
135 | }
136 |
137 | public void setHttpMethod(String httpMethod) {
138 | this.httpMethod = httpMethod;
139 | }
140 |
141 | public Object getHeaders() {
142 | return headers;
143 | }
144 |
145 | public void setHeaders(Object headers) {
146 | this.headers = headers;
147 | }
148 |
149 | public String getTag() {
150 | return tag;
151 | }
152 |
153 | public void setTag(String tag) {
154 | this.tag = tag;
155 | }
156 |
157 | public String getContent() {
158 | return content;
159 | }
160 |
161 | public void setContent(String content) {
162 | this.content = content;
163 | }
164 |
165 | public String getMethod() {
166 | return method;
167 | }
168 |
169 | public void setMethod(String method) {
170 | this.method = method;
171 | }
172 |
173 | public Object getArgs() {
174 | return args;
175 | }
176 |
177 | public void setArgs(Object args) {
178 | this.args = args;
179 | }
180 |
181 | public Object getRespBody() {
182 | return respBody;
183 | }
184 |
185 | public void setRespBody(Object respBody) {
186 | this.respBody = respBody;
187 | }
188 |
189 | public Date getLogDate() {
190 | return logDate == null ? null : (Date) logDate.clone();
191 | }
192 |
193 | public void setLogDate(Date logDate) {
194 | if (logDate != null) {
195 | this.logDate = (Date) logDate.clone();
196 | }
197 | }
198 |
199 | public long getCostTime() {
200 | return costTime;
201 | }
202 |
203 | public void setCostTime(long costTime) {
204 | this.costTime = costTime;
205 | }
206 |
207 | public String getThreadName() {
208 | return threadName;
209 | }
210 |
211 | public void setThreadName(String threadName) {
212 | this.threadName = threadName;
213 | }
214 |
215 | public long getThreadId() {
216 | return threadId;
217 | }
218 |
219 | public void setThreadId(long threadId) {
220 | this.threadId = threadId;
221 | }
222 |
223 | public boolean isSuccess() {
224 | return success;
225 | }
226 |
227 | public void setSuccess(boolean success) {
228 | this.success = success;
229 | }
230 |
231 | /**
232 | * 获取当前线程中的操作日志对象
233 | *
234 | * @return Gets the LogData in the current thread
235 | */
236 | protected static LogData getCurrent() {
237 | if (LOG_DATA.get() == null) {
238 | LogData logData = new LogData();
239 | logData.setLogDate(new Date());
240 | StringBuilder sb = CONTENT_BUILDER.get();
241 | if (sb == null) {
242 | CONTENT_BUILDER.set(new StringBuilder());
243 | }
244 | LOG_DATA.set(logData);
245 | }
246 | return LOG_DATA.get();
247 | }
248 |
249 | /**
250 | * 设置当前线程中的操作日志对象
251 | *
252 | * @param logData AopLog日志对象
253 | */
254 | protected static void setCurrent(LogData logData) {
255 | if (CONTENT_BUILDER.get() != null) {
256 | logData.setContent(CONTENT_BUILDER.get().toString());
257 | }
258 | LOG_DATA.set(logData);
259 | }
260 |
261 | /**
262 | * 移除当前线程AopLog日志对象
263 | */
264 | public static void removeCurrent() {
265 | CONTENT_BUILDER.remove();
266 | LOG_DATA.remove();
267 | }
268 |
269 | /**
270 | * 内容记录记录
271 | *
272 | * @param step 这里可以使用 该方法记录每一个步骤
273 | */
274 | public static void step(String step) {
275 | StringBuilder sb = CONTENT_BUILDER.get();
276 | if (sb != null) {
277 | sb.append(step).append("\n");
278 | CONTENT_BUILDER.set(sb);
279 | }
280 | }
281 |
282 | /**
283 | * 内容记录步骤记录 例如 step("ABC--{}--EFG ", "D") ABC--D--EFG
284 | *
285 | * @param stepTemplate step模板 该方法记录每一个步骤
286 | * @param args 模板参数
287 | */
288 | public static void step(String stepTemplate, Object... args) {
289 | step(MessageFormatter.format(stepTemplate, args));
290 | }
291 |
292 | }
293 |
--------------------------------------------------------------------------------
/src/main/java/com/github/LogDataAspect.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import org.aspectj.lang.ProceedingJoinPoint;
4 | import org.aspectj.lang.annotation.Around;
5 | import org.aspectj.lang.annotation.Aspect;
6 | import org.aspectj.lang.annotation.Pointcut;
7 | import org.aspectj.lang.reflect.MethodSignature;
8 | import org.springframework.context.annotation.ComponentScan;
9 | import org.springframework.context.annotation.EnableAspectJAutoProxy;
10 | import org.springframework.stereotype.Component;
11 |
12 | import javax.annotation.Resource;
13 |
14 | /**
15 | * @author EalenXie Created on 2020/1/2 17:52.
16 | * LogData Aspect
17 | */
18 | @ComponentScan
19 | @Component
20 | @Aspect
21 | @EnableAspectJAutoProxy(exposeProxy = true)
22 | public final class LogDataAspect {
23 |
24 | @Resource
25 | private AopLogProcessor aopLogProcessor;
26 |
27 | /**
28 | * 将会切 被AopLog注解标记的方法
29 | */
30 | @Pointcut("@annotation(AopLog) || @within(AopLog)")
31 | public void aopLogPointCut() {
32 | //ig
33 | }
34 |
35 | @Around("aopLogPointCut()")
36 | public Object note(ProceedingJoinPoint point) throws Throwable {
37 | AopLogConfig config = new AopLogConfig();
38 | MethodSignature signature = (MethodSignature) point.getSignature();
39 | AopLog aopLog = signature.getMethod().getAnnotation(AopLog.class);
40 | if (aopLog == null) {
41 | aopLog = point.getTarget().getClass().getAnnotation(AopLog.class);
42 | }
43 | if (aopLog != null) {
44 | config.setLogOnErr(aopLog.logOnErr());
45 | config.setTag(aopLog.tag());
46 | config.setHeaders(aopLog.headers());
47 | config.setArgs(aopLog.args());
48 | config.setRespBody(aopLog.respBody());
49 | config.setStackTraceOnErr(aopLog.stackTraceOnErr());
50 | config.setAsyncMode(aopLog.asyncMode());
51 | config.setCollector(aopLog.collector());
52 | }
53 | return aopLogProcessor.proceed(config, point);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/github/MessageFormatter.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | /**
4 | * @author EalenXie create on 2020/10/29 9:44
5 | * 例如 format("ABC--{}--EFG ", "D") ABC--D--EFG
6 | */
7 | public final class MessageFormatter {
8 |
9 | private static final String DELIMITER = "{}";
10 |
11 | private static final String ESCAPE_CHAR = "\\";
12 |
13 | private static final String EMPTY = "";
14 |
15 | private MessageFormatter() {
16 |
17 | }
18 |
19 | public static String format(String template, Object... args) {
20 | if (args == null || args.length <= 0) {
21 | return template;
22 | }
23 | if (template == null || template.isEmpty()) {
24 | return EMPTY;
25 | }
26 | if (template.contains(DELIMITER)) {
27 | StringBuilder buf = new StringBuilder(template);
28 | int start = 0;
29 | for (Object arg : args) {
30 | int result = escapeReplace(DELIMITER, ESCAPE_CHAR, buf, arg, start);
31 | start = result;
32 | if (result == -1) {
33 | break;
34 | }
35 | }
36 | return buf.toString();
37 | }
38 | return template;
39 | }
40 |
41 |
42 | public static int escapeReplace(String delimiter, String escape, StringBuilder buf, Object arg, int start) {
43 | int esIndex = buf.indexOf(escape + delimiter, start);
44 | int deIndex = buf.indexOf(delimiter, start);
45 | if (esIndex == -1) {
46 | if (deIndex != -1) {
47 | int di = deIndex + delimiter.length();
48 | buf.replace(deIndex, di, arg.toString());
49 | return di;
50 | } else {
51 | return -1;
52 | }
53 | } else {
54 | if (esIndex > deIndex) {
55 | int di = deIndex + delimiter.length();
56 | buf.replace(deIndex, di, arg.toString());
57 | return di;
58 | } else {
59 | buf.replace(esIndex, esIndex + escape.length(), EMPTY);
60 | return escapeReplace(delimiter, escape, buf, arg, esIndex + (escape + delimiter).length());
61 | }
62 | }
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/github/SpringElSupporter.java:
--------------------------------------------------------------------------------
1 | package com.github;
2 |
3 | import org.springframework.context.expression.MethodBasedEvaluationContext;
4 | import org.springframework.core.DefaultParameterNameDiscoverer;
5 | import org.springframework.core.ParameterNameDiscoverer;
6 | import org.springframework.expression.Expression;
7 | import org.springframework.expression.spel.standard.SpelExpressionParser;
8 | import org.springframework.util.StringUtils;
9 |
10 | import java.lang.reflect.Method;
11 | import java.util.HashMap;
12 | import java.util.Map;
13 | import java.util.regex.Matcher;
14 | import java.util.regex.Pattern;
15 |
16 | /**
17 | * Created by EalenXie on 2021/7/12 13:45
18 | * 支持SpringEL
19 | */
20 | public class SpringElSupporter {
21 |
22 | private final SpelExpressionParser parser = new SpelExpressionParser();
23 | private final ParameterNameDiscoverer paramNameDiscoverer = new DefaultParameterNameDiscoverer();
24 | private final Map expressions = new HashMap<>();
25 | private final Pattern pattern = Pattern.compile("^[^/:*+?|<>=#${}\\[\\]-]+$");
26 |
27 | public Object getByExpression(Method method, Object target, Object[] args, String expressionString) {
28 | try {
29 | if (StringUtils.hasText(expressionString)) {
30 | Matcher matcher = pattern.matcher(expressionString);
31 | if (!matcher.find()) {
32 | Expression expression;
33 | MethodBasedEvaluationContext evaluationContext = new MethodBasedEvaluationContext(new ExpressionRootObject(target, args), method, args, paramNameDiscoverer);
34 | if (expressions.containsKey(expressionString)) {
35 | return expressions.get(expressionString).getValue(evaluationContext);
36 | } else {
37 | expression = parser.parseExpression(expressionString);
38 | Object value = expression.getValue(evaluationContext);
39 | expressions.put(expressionString, expression);
40 | return value;
41 | }
42 | }
43 | }
44 | } catch (Exception e) {
45 | // ignore any exception
46 | }
47 | return expressionString;
48 | }
49 |
50 | static class ExpressionRootObject {
51 |
52 | private Object target;
53 |
54 | private Object[] args;
55 |
56 | public ExpressionRootObject(Object target, Object[] args) {
57 | this.target = target;
58 | this.args = args;
59 | }
60 |
61 | public Object getTarget() {
62 | return target;
63 | }
64 |
65 | public void setTarget(Object target) {
66 | this.target = target;
67 | }
68 |
69 | public Object[] getArgs() {
70 | return args;
71 | }
72 |
73 | public void setArgs(Object[] args) {
74 | this.args = args;
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/com/github/collector/LogCollector.java:
--------------------------------------------------------------------------------
1 | package com.github.collector;
2 |
3 |
4 | import com.github.Collector;
5 | import com.github.LogData;
6 |
7 | /**
8 | * @author EalenXie Created on 2020/1/7 9:12.
9 | * 日志收集器
10 | */
11 | public interface LogCollector extends Collector {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/github/collector/NothingCollector.java:
--------------------------------------------------------------------------------
1 | package com.github.collector;
2 |
3 |
4 | import com.github.LogData;
5 |
6 | /**
7 | * @author EalenXie Created on 2020/1/13 18:00.
8 | * An empty collector is provided by default
9 | */
10 | public class NothingCollector implements LogCollector {
11 | @Override
12 | public void collect(LogData data) {
13 | // This is an empty collector will do nothing
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/spring.factories:
--------------------------------------------------------------------------------
1 | # Auto Configure
2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
3 | com.github.AopLogProcessor,\
4 | com.github.LogDataAspect,\
5 | com.github.AopLogAutoConfiguration
6 |
7 |
--------------------------------------------------------------------------------