前言
請問今天您便祕了嗎?程式設計師坐久了真的會便祕哦,如果偶然點進了這篇小乾貨,就麻煩您喝杯水然後去趟廁所一邊用左手托起對準噓噓,一邊用右手滑動手機看完本篇吧。
實現
本篇AOP統一日誌管理寫法來源於國外知名開源框架JHipster的AOP日誌管理方式
1、引入依賴
<!-- spring aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、定義logback配置
1)、dev、test環境的spring-web包定義日誌級別為INFO,專案包定義日誌級別為DEBUG;
2)、prod環境的spring-web包定義日誌級別為ERROR,專案包定義日誌級別為INFO;
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="TRACE" />
<springProfile name="dev,test">
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="INFO" />
<logger name="com.example.aoplog" level="DEBUG" />
</springProfile>
<springProfile name="prod">
<logger name="org.springframework.web" level="ERROR"/>
<logger name="org.springboot.sample" level="ERROR" />
<logger name="com.example.aoplog" level="INFO" />
</springProfile>
</configuration>
3、編寫切面類
1)、springBeanPointcut():單獨定義的spring框架切入點;
2)、applicationPackagePointcut():單獨定義的專案包切入點;
3)、logAfterThrowing():1和2定義的切入點丟擲異常時日誌格式及顯示內容;
4)、logAround():1和2定義的切入點方法進入和退出時日誌格式及顯示內容。
package com.example.aoplog.logging;
import com.example.aoplog.constants.GloablConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* <p>
* AOP統一日誌管理 切面類
* </p>
*
* @author 福隆苑居士,公眾號:【Java分享客棧】
* @since 2022/5/5 21:57
*/
@Aspect
@Component
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* 匹配spring框架的repositories、service、rest端點的切面
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)")
public void springBeanPointcut() {
// 方法為空,因為這只是一個切入點,實現在通知中。
}
/**
* 匹配我們自己專案的repositories、service、rest端點的切面
*/
@Pointcut("within(com.example.aoplog.repository..*)"+
" || within(com.example.aoplog.service..*)"+
" || within(com.example.aoplog.controller..*)")
public void applicationPackagePointcut() {
// 方法為空,因為這只是一個切入點,實現在通知中。
}
/**
* 記錄方法丟擲異常的通知
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
// 判斷環境,dev、test or prod
if (env.acceptsProfiles(Profiles.of(GloablConstants.SPRING_PROFILE_DEVELOPMENT, GloablConstants.SPRING_PROFILE_TEST))) {
log.error("Exception in {}.{}() with cause = '{}' and exception = '{}'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
/**
* 在方法進入和退出時記錄日誌的通知
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
}
4、測試
1)、寫個service
package com.example.aoplog.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* <p>
* AOP統一日誌管理測試服務
* </p>
*
* @author 福隆苑居士,公眾號:【Java分享客棧】
* @since 2022/5/5 21:57
*/
@Service
@Slf4j
public class AopLogService {
public String test(Integer id) {
return "傳入的引數是:" + id;
}
}
2)、寫個controller
package com.example.aoplog.controller;
import com.example.aoplog.service.AopLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 測試介面
* </p>
*
* @author 福隆苑居士,公眾號:【Java分享客棧】
* @since 2022/4/30 11:43
*/
@RestController
@RequestMapping("/api")
@Slf4j
public class TestController {
private final AopLogService aopLogService;
public TestController(AopLogService aopLogService) {
this.aopLogService = aopLogService;
}
@GetMapping("/test/{id}")
public ResponseEntity<String> test(@PathVariable("id") Integer id) {
return ResponseEntity.ok().body(aopLogService.test(id));
}
}
3)、設定環境
這裡我試試dev,prod自己試聽見沒?不服一拳打哭你哦!
server:
port: 8888
# 環境:dev-開發 test-測試 prod-生產
spring:
profiles:
active: dev
4)、效果
不解釋了自己看
試試異常情況,手動加個異常。
@Service
@Slf4j
public class AopLogService {
public String test(Integer id) {
int i = 1/0;
return "傳入的引數是:" + id;
}
}
效果
總結
OK!打完收工!
連結:https://pan.baidu.com/doc/share/flr0QYwZYPYxmWSRPbnJRw-1028798558141759
提取碼:bxaa
記住,別點贊,別推薦,別關注 ,好好上個廁所喝杯水,你們今天下班前能拉出來我就心滿意足了。