通过注解和切面实现日志记录

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoLog {
    boolean inLog() default true;

    boolean outLog() default true;

    AutoLogLevelEnum level() default NONE;

}


/**
 * projectName micro-util
 * package com.open.util.handler.aspect
 * classname  AutoLogAspect
 * <p>
 * description
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2021/7/2 18:00
 */
@Slf4j
@Aspect
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class AutoLogAspect {
    @Value("${open.advice.log.enabled:true}")
    private boolean logEnabled;

    @Value("${open.advice.log.logging.level:DEBUG}")
    private AutoLogLevelEnum loggingLevel;

    @Pointcut("@annotation(com.com.open.util.entity.annotation.AutoLog)")
    private void allRequestMethod() {
    }

    @Before("allRequestMethod()")
    public void doBefore(JoinPoint joinPoint) {
        if (!logEnabled) {
            return;
        }
        AutoLog autoLog = getAutoLog(joinPoint);
        if (!autoLog.inLog()) {
            return;
        }
        AutoLogLevelEnum logLevel = Objects.equals(autoLog.level(), NONE) ? loggingLevel : autoLog.level();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Optional.ofNullable(attributes).ifPresent(attribute -> {
            HttpServletRequest request = attribute.getRequest();
            request.getRequestURI();
            request.getRemoteAddr();
            logManage(logLevel, "Request uri [{}],remote addr {}", request.getRequestURI(), request.getRemoteAddr());
        });
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        logManage(logLevel, "In log method:[{}],args [{}]", method, args);
    }

    @AfterReturning(value = "allRequestMethod()", returning = "returnValue")
    public void doAfter(JoinPoint joinPoint, Object returnValue) {
        if (!logEnabled) {
            return;
        }
        AutoLog aroundLogger = getAutoLog(joinPoint);
        if (!aroundLogger.outLog()) {
            return;
        }
        AutoLogLevelEnum logLevel = Objects.equals(aroundLogger.level(), NONE) ? loggingLevel : aroundLogger.level();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        logManage(logLevel, "Out log method:[{}],return [{}]", method, returnValue);
    }


    private AutoLog getAutoLog(JoinPoint point) {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        AutoLog result = method.getAnnotation(AutoLog.class);
        if (Objects.isNull(result)) {
            return method.getDeclaringClass().getAnnotation(AutoLog.class);
        }
        return result;
    }

    private void logManage(AutoLogLevelEnum level, String market, Object... args) {
        switch (level) {
            case WARN:
                log.warn(market, args);
                break;
            case DEBUG:
                log.debug(market, args);
                break;
            default:
                log.info(market, args);
        }
    }
}
上一篇:logback配置文件


下一篇:无影使用体验