SpringBoot詳解系列文章:
SpringBoot詳解(一)-快速入門
SpringBoot詳解(二)-Spring Boot的核心
SpringBoot詳解(三)-Spring Boot的web開發(fā)
SpringBoot詳解(四)-優(yōu)雅地處理日志
一、簡(jiǎn)介
日志功能在j2ee項(xiàng)目中是一個(gè)相當(dāng)常見的功能,在一個(gè)小項(xiàng)目中或許你可以在一個(gè)個(gè)方法中,使用日志表的Mapper生成一條條的日志記錄,但這無非是最爛的做法之一,因?yàn)檫@種做法會(huì)讓日志Mapper分布到了項(xiàng)目的多處代碼中,后續(xù)很難管理。而對(duì)于大型的項(xiàng)目而言,這種做法根本不能采用。本篇文章將介紹,使用自定義注解,配合AOP,優(yōu)雅的完成日志功能。
本文Demo使用的是Spring Boot框架,但并非只針對(duì)Spring Boot,如果你的項(xiàng)目用的是Spring MVC,做下簡(jiǎn)單的轉(zhuǎn)換即可在你的項(xiàng)目中實(shí)現(xiàn)相同的功能。
二、日志管理的實(shí)現(xiàn)
在開始編碼之前,先介紹下思路:
在Service層中,涉及到大量業(yè)務(wù)邏輯操作,我們往往就需要在一個(gè)業(yè)務(wù)操作完成后(不管成敗或失?。?,生成一條日志,并插入到數(shù)據(jù)庫中。那么我們可以在這些涉及到業(yè)務(wù)操作的方法上使用一個(gè)自定義注解進(jìn)行標(biāo)記,同時(shí)將日志記錄到注解中。再配合Spring的AOP功能,在監(jiān)聽到該方法執(zhí)行之后,獲取到注解內(nèi)的日志信息,把這條日志插入到數(shù)據(jù)即可。
好了,下面就對(duì)上面的理論付出實(shí)踐。
1、自定義注解
這里我們自定義一個(gè)日志注解,該注解中的logStr屬性將用來保存日志信息。自定義注解代碼如下:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
@Documented
public @interface Log {
String logStr() default "";
}
2、使用自定義注解
接著就是到Service層中,在需要使用到日志功能的方法上加上該注解。如果業(yè)務(wù)需求是在添加一個(gè)用戶之后,記錄一條日志,那只需要在添加用戶的方法上加上這個(gè)自定義注解即可。代碼如下:
@Service
public class UserService {
@Log(logStr = "添加一個(gè)用戶")
public Result add(User user) {
return ResultUtils.success();
}
}
3、使用AOP統(tǒng)一處理日志
前面的自定義注解只是起到一個(gè)標(biāo)記與存儲(chǔ)日志的作用,接下來需要就該使用Spring的AOP功能,攔截方法的執(zhí)行,通過反射獲取到注解及注解中所包含的日志信息。
如果你不清楚怎么在Spring Boot中使用AOP功能,建議你去看上一篇文章:SpringBoot詳解(三)-Spring Boot的web開發(fā),這里不再贅訴。
因?yàn)榇a量不大,就不多廢話了,直接貼出日志切面的完整代碼,詳細(xì)情況看代碼中的注釋:
@Component
@Aspect
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(LogAspect.class);
// 設(shè)置切點(diǎn)表達(dá)式
@Pointcut("execution(* com.lqr.service..*(..))")
private void pointcut() {
}
// 方法后置切面
@After(value = "pointcut()")
public void After(JoinPoint joinPoint) throws NotFoundException, ClassNotFoundException {
// 拿到切點(diǎn)的類名、方法名、方法參數(shù)
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
// 反射加載切點(diǎn)類,遍歷類中所有的方法
Class<?> targetClass = Class.forName(className);
Method[] methods = targetClass.getMethods();
for (Method method : methods) {
// 如果遍歷到類中的方法名與切點(diǎn)的方法名一致,并且參數(shù)個(gè)數(shù)也一致,就說明切點(diǎn)找到了
if (method.getName().equalsIgnoreCase(methodName)) {
Class<?>[] clazzs = method.getParameterTypes();
if (clazzs.length == args.length) {
// 獲取到切點(diǎn)上的注解
Log logAnnotation = method.getAnnotation(Log.class);
if (logAnnotation != null) {
// 獲取注解中的日志信息,并輸出
String logStr = logAnnotation.logStr();
logger.error("獲取日志:" + logStr);
// 數(shù)據(jù)庫記錄操作...
break;
}
}
}
}
}
}
4、驗(yàn)證
為了驗(yàn)證這種方式是否真的能拿到注解中攜帶的日志信息,這里創(chuàng)建一個(gè)Controller,代碼如下:
@RestController
public class UserController {
@Autowired
UserService mUserService;
@PostMapping("/add")
public Result add(User user) throws NotFoundException {
return mUserService.add(user);
}
}
使用postman訪問接口,可以看到注解中的日志信息確實(shí)被拿到了。

你以為這樣就結(jié)束了嗎?不,這僅僅只是實(shí)現(xiàn)了日志功能,但稱不上優(yōu)雅,因?yàn)榇嬖诓环奖愕牡胤剑旅婢驼f下,如何對(duì)這種方式進(jìn)一步優(yōu)化,從而做到優(yōu)雅的處理日志功能。
三、優(yōu)化日志功能
1、分析
前面確確實(shí)實(shí)的使用自定義注解和AOP做到了日志功能,但存在什么問題呢?這個(gè)問題不是代碼問題,而是業(yè)務(wù)功能問題。開發(fā)中可能有以下幾種情況:
- 假設(shè)公司的業(yè)務(wù)是不僅僅只是記錄某個(gè)用戶使用該系統(tǒng)做了什么操作,還需要記錄在操作的過程中出現(xiàn)過什么問題。
- 假設(shè)日志的內(nèi)容,不可以在注解中寫死,要可以在代碼中自由設(shè)置日志信息。
簡(jiǎn)而言之,就是日志內(nèi)容可以在代碼中隨意修改。這就有問題了,注解是靜態(tài)侵入的,要怎么才能做到在代碼中動(dòng)態(tài)修改注解中的屬性值呢?所幸,javassist可以幫我們做到這一點(diǎn),下面就來看看,如果實(shí)現(xiàn)該功能。
javassist需要自己導(dǎo)入第三方依賴,如果你項(xiàng)目有使用到Spring Boot的模板功能(thymeleaf),則無須添加依賴。
2、完善與增強(qiáng)
1)封裝AnnotationUtils
結(jié)合網(wǎng)上查閱到的資料,我對(duì)使用javassist動(dòng)態(tài)修改方法上注解及查看注解中屬性值的功能做了一個(gè)封裝,工具類名為:AnnotationUtils(和Spring自帶的一個(gè)類名字一樣,注意不要在代碼中導(dǎo)錯(cuò)包了),并使用了單例模式。代碼如下:
/**
* @創(chuàng)建者 CSDN_LQR
* @描述 注解中屬性修改、查看工具
*/
public class AnnotationUtils {
private static AnnotationUtils mInstance;
public AnnotationUtils() {
}
public static AnnotationUtils get() {
if (mInstance == null) {
synchronized (AnnotationUtils.class) {
if (mInstance == null) {
mInstance = new AnnotationUtils();
}
}
}
return mInstance;
}
/**
* 修改注解上的屬性值
*
* @param className 當(dāng)前類名
* @param methodName 當(dāng)前方法名
* @param annoName 方法上的注解名
* @param fieldName 注解中的屬性名
* @param fieldValue 注解中的屬性值
* @throws NotFoundException
*/
public void setAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName, String fieldValue) throws NotFoundException {
ClassPool classPool = ClassPool.getDefault();
CtClass ct = classPool.get(className);
CtMethod ctMethod = ct.getDeclaredMethod(methodName);
MethodInfo methodInfo = ctMethod.getMethodInfo();
ConstPool constPool = methodInfo.getConstPool();
AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
Annotation annotation = attr.getAnnotation(annoName);
if (annotation != null) {
annotation.addMemberValue(fieldName, new StringMemberValue(fieldValue, constPool));
attr.setAnnotation(annotation);
methodInfo.addAttribute(attr);
}
}
/**
* 獲取注解中的屬性值
*
* @param className 當(dāng)前類名
* @param methodName 當(dāng)前方法名
* @param annoName 方法上的注解名
* @param fieldName 注解中的屬性名
* @return
* @throws NotFoundException
*/
public String getAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName) throws NotFoundException {
ClassPool classPool = ClassPool.getDefault();
CtClass ct = classPool.get(className);
CtMethod ctMethod = ct.getDeclaredMethod(methodName);
MethodInfo methodInfo = ctMethod.getMethodInfo();
AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
String value = "";
if (attr != null) {
Annotation an = attr.getAnnotation(annoName);
if (an != null)
value = ((StringMemberValue) an.getMemberValue(fieldName)).getValue();
}
return value;
}
}
2)封裝LogUtils
通過上面的工具類(AnnotationUtils)雖然可以實(shí)現(xiàn)在代碼中動(dòng)態(tài)修改注解中的屬性值的功能,但AnnotationUtils方法中需要的參數(shù)過多,這里對(duì)其做一層封裝,不需要在代碼中考慮類名、方法名的獲取,方便開發(fā)。
/**
* @創(chuàng)建者 CSDN_LQR
* @描述 日志修改工具
*/
public class LogUtils {
private static LogUtils mInstance;
private LogUtils() {
}
public static LogUtils get() {
if (mInstance == null) {
synchronized (LogUtils.class) {
if (mInstance == null) {
mInstance = new LogUtils();
}
}
}
return mInstance;
}
public void setLog(String logStr) throws NotFoundException {
String className = Thread.currentThread().getStackTrace()[2].getClassName();
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
AnnotationUtils.get().setAnnotatioinFieldValue(className, methodName, Log.class.getName(), "logStr", logStr);
}
}
3)Service中根據(jù)情況動(dòng)態(tài)修改日志信息
@Service
public class UserService {
@Log(logStr = "添加一個(gè)用戶")
public Result add(User user) throws NotFoundException {
if (user.getAge() < 18) {
LogUtils.get().setLog("添加用戶失敗,因?yàn)橛脩粑闯赡?);
return ResultUtils.error("未成年不能注冊(cè)");
}
if ("男".equalsIgnoreCase(user.getSex())) {
LogUtils.get().setLog("添加用戶失敗,因?yàn)橛脩羰莻€(gè)男的");
return ResultUtils.error("男性不能注冊(cè)");
}
LogUtils.get().setLog("添加用戶成功,是一個(gè)" + user.getAge() + "歲的美少女");
return ResultUtils.success();
}
}
4)修改日志切面
使用javassist修改過的注解屬性值無法通過java反射正確靜態(tài)獲取,還需要借助javassist來動(dòng)態(tài)獲取,所以,LogAspect中的代碼修改如下:
@Component
@Aspect
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("execution(* com.lqr.service..*(..))")
private void pointcut() {
}
@After(value = "pointcut()")
public void After(JoinPoint joinPoint) throws NotFoundException, ClassNotFoundException {
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
String logStr = AnnotationUtils.get().getAnnotatioinFieldValue(className, methodName, Log.class.getName(), "logStr");
if (!StringUtils.isEmpty(logStr)) {
logger.error("獲取日志:" + logStr);
// 數(shù)據(jù)庫記錄操作...
}
}
}
3、驗(yàn)證
上面代碼都編寫完了,下面就驗(yàn)證下,是否可以根據(jù)業(yè)務(wù)情況動(dòng)態(tài)注解中的屬性值吧。


