カスタムログ注記(メソッド名、パラメータなどを取得可能)


ここでは主にspringのAOPに依存して実現されているが,springを参照していなければこの方式は使用できない.
一、導入依存
 
     org.springframework.boot
     spring-boot-starter-aop
 

 
     org.apache.commons
     commons-lang3
     3.9
 

二、カスタムログ注記
package com.example.demo.log;

import java.lang.annotation.*;

/**
 *     startLog、endLog、errorLog      ,      ,      operate
 * startLog:        
 * endLog:          
 * errorLog:    
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperateLog {

    String startLog() default ""; //          

    String endLog() default ""; //         

    String operate() default "";//  

    String errorLog() default "";//    

}

三、ログ注記解析クラスの作成
package com.example.demo.log;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 *        ,            ,         ,
 */
@Aspect
@Component
@Slf4j
public class OperateLogResolver {

    /**
     *   
     */
    private final String EXECUTION = "@annotation(com.example.demo.log.OperateLog)";

    @Around(EXECUTION)
    public Object arround(ProceedingJoinPoint joinPoint) throws Throwable {

        //        
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        String className = joinPoint.getSignature().getDeclaringTypeName();

        String methodName = String.format("%s.%s", className, method.getName());

        //      
        OperateLog upgradeProgress = method.getAnnotation(OperateLog.class);

        String operate = upgradeProgress.operate(); //     

        //    
        String startLog = StringUtils.defaultIfBlank(upgradeProgress.startLog(), StringUtils.isNotEmpty(operate) ? String.format("start %s", operate) : String.format("start execute %s", methodName));

        //    
        String endLog = StringUtils.defaultIfBlank(upgradeProgress.endLog(), StringUtils.isNotEmpty(operate) ? String.format("execute %s successfully", operate) : String.format("execute %s successfully", methodName));

        //    
        String errorLog = StringUtils.defaultIfBlank(upgradeProgress.errorLog(), StringUtils.isNotEmpty(operate) ? String.format("execute %s error", operate) : String.format("execute %s error", methodName));


        //         
        log.info(startLog);

        //      
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); //   

        //    :
        final Object[] argValues = joinPoint.getArgs();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < argNames.length; i++) {
            String value = argValues[i] == null ? "null" : argValues[i].toString();
            sb.append(argNames[i]).append("=").append(value).append(",");
        }
        String paramStr = sb.length() > 0 ? sb.toString().substring(0, sb.length() - 1) + "]" : "";
        log.info("     :[ {}", paramStr);

        //    
        Object result = null;

        try {
            result = joinPoint.proceed();
        } catch (Exception e) {
            log.error(errorLog, e);

        }

        String resultStr = result == null ? "null" : result.toString();
        log.info("     :{}",resultStr);

        //         
        log.info(endLog);

        return result;
    }

}

四、ログ注釈の使用
@OperateLog(
         operate = "update user"
 )
 public User updateUser(User user,String greet) {
     System.out.println(greet);
     user.setAge(user.getAge() + 2);
     user.setName(StringUtils.defaultIfBlank("NULL NAME", StringUtils.upperCase(user.getName())));
     return user;
 }

印刷されたログ情報の内容は次のとおりです.
2019-11-11 20:31:48.004  INFO 10856 --- [nio-8080-exec-1] com.example.demo.log.OperateLogResolver  : start update user
2019-11-11 20:31:48.005  INFO 10856 --- [nio-8080-exec-1] com.example.demo.log.OperateLogResolver  :      :[ user=User(name=liuxing, age=20),greet=hello]
hello
2019-11-11 20:31:48.019  INFO 10856 --- [nio-8080-exec-1] com.example.demo.log.OperateLogResolver  :      :User(name=NULL NAME, age=22)
2019-11-11 20:31:48.019  INFO 10856 --- [nio-8080-exec-1] com.example.demo.log.OperateLogResolver  : execute update user successfully