當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot/Cloud AOP 统一日志输出
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot/Cloud AOP 统一日志输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 導入依賴
- 2. aop攔截器
- 3. logback配置
- 4. 測試類
- 5. 關鍵點
- 6. 效果圖
1. 導入依賴
<!-- AOP --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><!-- 數據序列化--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.78</version></dependency>2. aop攔截器
package com.course.server.config;import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.support.spring.PropertyPreFilters; import com.course.server.util.UuidUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Field;@Aspect @Component public class LogAspect {private final static Logger LOG = LoggerFactory.getLogger(LogAspect.class);/** 定義一個切點 */@Pointcut("execution(public * com.course.*.controller..*Controller.*(..))")public void controllerPointcut() {}@Before("controllerPointcut()")public void doBefore(JoinPoint joinPoint) throws Throwable {// 日志編號MDC.put("UUID", UuidUtil.getShortUuid());// 開始打印請求日志ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();Signature signature = joinPoint.getSignature();String name = signature.getName();// 打印業務操作String nameCn = "";if (name.contains("list") || name.contains("query")) {nameCn = "查詢";} else if (name.contains("save")) {nameCn = "保存";} else if (name.contains("delete")) {nameCn = "刪除";} else {nameCn = "操作";}// 使用反射,獲取業務名稱Class clazz = signature.getDeclaringType();Field field;String businessName = "";try {field = clazz.getField("BUSINESS_NAME");if (!StringUtils.isEmpty(field)) {businessName = (String) field.get(clazz);}} catch (NoSuchFieldException e) {LOG.error("未獲取到業務名稱");} catch (SecurityException e) {LOG.error("獲取業務名稱失敗", e);}// 打印請求信息LOG.info("------------- 【{}】{}開始 -------------", businessName, nameCn);LOG.info("請求地址: {} {}", request.getRequestURL().toString(), request.getMethod());LOG.info("類名方法: {}.{}", signature.getDeclaringTypeName(), name);LOG.info("遠程地址: {}", request.getRemoteAddr());// 打印請求參數Object[] args = joinPoint.getArgs();Object[] arguments = new Object[args.length];for (int i = 0; i < args.length; i++) {if (args[i] instanceof ServletRequest|| args[i] instanceof ServletResponse|| args[i] instanceof MultipartFile) {continue;}arguments[i] = args[i];}// 排除字段,敏感字段或太長的字段不顯示String[] excludeProperties = {"shard"};PropertyPreFilters filters = new PropertyPreFilters();PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();excludefilter.addExcludes(excludeProperties);LOG.info("請求參數: {}", JSONObject.toJSONString(arguments, excludefilter)); // 為空的會不打印,但是像圖片等長字段也會打印}@Around("controllerPointcut()")public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {long startTime = System.currentTimeMillis();Object result = proceedingJoinPoint.proceed();// 排除字段,敏感字段或太長的字段不顯示String[] excludeProperties = {"password", "shard"};PropertyPreFilters filters = new PropertyPreFilters();PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();excludefilter.addExcludes(excludeProperties);LOG.info("返回結果: {}", JSONObject.toJSONString(result, excludefilter));LOG.info("------------- 結束 耗時:{} ms -------------", System.currentTimeMillis() - startTime);return result;}}3. logback配置
logback.xml
4. 測試類
package com.course.business.controller.admin;import com.course.server.dto.ChapterDto; import com.course.server.dto.PageDto; import com.course.server.dto.ResponseDto; import com.course.server.service.ChapterService; import com.course.server.util.ValidatorUtil; import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;@RestController @RequestMapping("/admin/chapter") public class ChapterController {// 業務標識public static final String BUSINESS_NAME = "大章";@Resourceprivate ChapterService chapterService;//http://127.0.0.1:9002/business/admin/chapter/list@PostMapping("/list")public ResponseDto list(@RequestBody PageDto pageDto) {ResponseDto responseDto = new ResponseDto();chapterService.list(pageDto);responseDto.setContent(pageDto);return responseDto;}@PostMapping("/save")public ResponseDto save(@RequestBody ChapterDto chapterDto) {// 保存校驗ValidatorUtil.require(chapterDto.getName(), "名稱");ValidatorUtil.require(chapterDto.getCourseId(), "課程ID");ValidatorUtil.length(chapterDto.getCourseId(), "課程ID", 1, 8);ResponseDto responseDto = new ResponseDto();chapterService.save(chapterDto);responseDto.setContent(chapterDto);return responseDto;}@DeleteMapping("/delete/{id}")public ResponseDto delete(@PathVariable String id) {ResponseDto responseDto = new ResponseDto();chapterService.delete(id);return responseDto;} }5. 關鍵點
LogAspect中日志key “UUID”要和logback.xml中的獲取的key UUID要一致,UUID生成規則自定義
6. 效果圖
總結
以上是生活随笔為你收集整理的SpringBoot/Cloud AOP 统一日志输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Maven 操作手册
- 下一篇: centos6.x redhat6.x