@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoLog {
boolean inLog() default true;
boolean outLog() default true;
AutoLogLevelEnum level() default NONE;
}
@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);
}
}
}