SpringBoot使用AOP統(tǒng)一日志管理的方法詳解
前言
請問今天您便秘了嗎?程序員坐久了真的會便秘哦,如果偶然點進(jìn)了這篇小干貨,就麻煩您喝杯水然后去趟廁所一邊用左手托起對準(zhǔn)噓噓,一邊用右手滑動手機(jī)看完本篇吧。
實現(xiàn)
本篇AOP統(tǒng)一日志管理寫法來源于國外知名開源框架JHipster的AOP日志管理方式
1、引入依賴
<!-- spring aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、定義logback配置
1)dev、test環(huán)境的spring-web包定義日志級別為INFO,項目包定義日志級別為DEBUG;
2)prod環(huán)境的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定義的切入點拋出異常時日志格式及顯示內(nèi)容;
4)logAround():1和2定義的切入點方法進(jìn)入和退出時日志格式及顯示內(nèi)容。
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統(tǒng)一日志管理 切面類
* </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() {
// 方法為空,因為這只是一個切入點,實現(xiàn)在通知中。
}
/**
* 匹配我們自己項目的repositories、service、rest端點的切面
*/
@Pointcut("within(com.example.aoplog.repository..*)"+
" || within(com.example.aoplog.service..*)"+
" || within(com.example.aoplog.controller..*)")
public void applicationPackagePointcut() {
// 方法為空,因為這只是一個切入點,實現(xiàn)在通知中。
}
/**
* 記錄方法拋出異常的通知
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
// 判斷環(huán)境,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");
}
}
/**
* 在方法進(jìn)入和退出時記錄日志的通知
*
* @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統(tǒng)一日志管理測試服務(wù)
* </p>
*
* @author 福隆苑居士,公眾號:【Java分享客?!?
* @since 2022/5/5 21:57
*/
@Service
@Slf4j
public class AopLogService {
public String test(Integer id) {
return "傳入的參數(shù)是:" + 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)設(shè)置環(huán)境
這里我試試dev,prod自己試聽見沒?不服一拳打哭你哦!
server:
port: 8888
# 環(huán)境:dev-開發(fā) test-測試 prod-生產(chǎn)
spring:
profiles:
active: dev
4)效果
不解釋了自己看

試試異常情況,手動加個異常。
@Service
@Slf4j
public class AopLogService {
public String test(Integer id) {
int i = 1/0;
return "傳入的參數(shù)是:" + id;
}
}
效果

到此這篇關(guān)于SpringBoot使用AOP統(tǒng)一日志管理的方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot AOP日志管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot增強(qiáng)Controller方法@ControllerAdvice注解的使用詳解
這篇文章主要介紹了SpringBoot增強(qiáng)Controller方法@ControllerAdvice注解的使用詳解,@ControllerAdvice,是Spring3.2提供的新注解,它是一個Controller增強(qiáng)器,可對controller進(jìn)行增強(qiáng)處理,需要的朋友可以參考下2023-10-10
GC調(diào)優(yōu)實戰(zhàn)之高分配速率High?Allocation?Rate
這篇文章主要為大家介紹了GC調(diào)優(yōu)之高分配速率High?Allocation?Rate的實戰(zhàn)示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-01-01
springboot實現(xiàn)string轉(zhuǎn)json json里面帶數(shù)組
這篇文章主要介紹了springboot實現(xiàn)string轉(zhuǎn)json json里面帶數(shù)組,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

