SpringAOP中基于注解實現(xiàn)通用日志打印方法詳解
前言
我們在日常開發(fā)中,項目里日志是必不可少的,一般有業(yè)務(wù)日志,數(shù)據(jù)庫日志,異常日志等,主要用于幫助程序猿后期排查一些生產(chǎn)中的bug。
有時候程序猿們在做代碼調(diào)優(yōu)的時候需要關(guān)注每個接口的響應(yīng)速度,所以需要打印接口調(diào)用時間,如果在接口中每次寫這段代碼實在惡心,故基于Spring AOP面向切面編程使用注解解決該問題。
1.定義注解
value為對應(yīng)的接口名稱,默認(rèn)為BaseController
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OwnLog {
String value() default "BaseController";
}2.面向切面處理
@Aspect
@Component
@Slf4j
public class LogAspect {
@Before(value = "@annotation(ownLog)")
public void before(JoinPoint point, OwnLog ownLog) {
//point.getArgs()獲取請求參數(shù)
log.info("服務(wù){(diào)}調(diào)用開始,請求參數(shù):{}", ownLog.value(), JSONObject.toJSONString(point.getArgs()));
}
@Around(value = "@annotation(ownLog)")
public Object around(ProceedingJoinPoint point, OwnLog ownLog) {
Object result = null;
String name = ownLog.value();
long start = System.currentTimeMillis();
try {
result = point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
long end = System.currentTimeMillis();
log.info(String.format("服務(wù)%s,耗時:%dms", name, (end - start)));
}
return result;
}
//設(shè)置rvt為返回參數(shù)
@AfterReturning(value = "@annotation(ownLog)", returning = "rvt")
public void afterReturning(JoinPoint point, OwnLog ownLog, Object rvt) {
log.info("服務(wù){(diào)}調(diào)用結(jié)束,response:{}", ownLog.value(), JSONObject.toJSONString(rvt));
}
}3.使用注解
@OwnLog("sendMsg")
@Idempotent
@ApiOperation(value = "消息推送")
@PostMapping(value = "/sendMsg")
public BaseResp sendMessage(@ModelAttribute UserMsgHistoryDTO userMsgHistoryDTO) {
userMsgHistoryService.sendMessage(findCurrentUser(), userMsgHistoryDTO);
addUserLog(LOG_TYPE_USER, "用戶消息推送", JSON.toJSONString(userMsgHistoryDTO));
return new BaseResp<>(ResultStatus.SUCCESS);
}4.控制臺打印
輸出:
服務(wù)addEnrolmentUser調(diào)用開始,request:[{"age":0,"country":"string","health":"一般","idNum":"12345","name":"string","phoneNum":"string","status":"審核中"}]
服務(wù)addEnrolmentUser,耗時:13ms
服務(wù)addEnrolmentUser調(diào)用結(jié)束,response:{"code":10000,"message":"操作成功","success":true}
到此這篇關(guān)于SpringAOP中基于注解實現(xiàn)通用日志打印方法詳解的文章就介紹到這了,更多相關(guān)SpringAOP注解實現(xiàn)日志打印內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Spring源碼報錯java:找不到類 InstrumentationSavingAgent的問題
這篇文章主要介紹了使用Spring源碼報錯java:找不到類 InstrumentationSavingAgent的問題,本文給大家分享解決方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
解決idea 通過build project 手動觸發(fā)熱部署失敗的問題
在debug運行項目的過程中,并且保證(不添加方法,不修改方法名)一定的規(guī)則的情況下,可以通過build project 來手動熱部署項目,本文給大家介紹解決idea 通過build project 手動觸發(fā)熱部署失敗的問題,感興趣的朋友一起看看吧2023-12-12

