@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documentedpublic@interfaceAutoLog {
booleaninLog() defaulttrue;
booleanoutLog() defaulttrue;
AutoLogLevelEnumlevel() defaultNONE;
}
@Slf4j@Aspect@Component@Order(Ordered.LOWEST_PRECEDENCE)
publicclassAutoLogAspect {
@Value("${open.advice.log.enabled:true}")
privatebooleanlogEnabled;
@Value("${open.advice.log.logging.level:DEBUG}")
privateAutoLogLevelEnumloggingLevel;
@Pointcut("@annotation(com.com.open.util.entity.annotation.AutoLog)")
privatevoidallRequestMethod() {
}
@Before("allRequestMethod()")
publicvoiddoBefore(JoinPointjoinPoint) {
if (!logEnabled) {
return;
}
AutoLogautoLog=getAutoLog(joinPoint);
if (!autoLog.inLog()) {
return;
}
AutoLogLevelEnumlogLevel=Objects.equals(autoLog.level(), NONE) ?loggingLevel : autoLog.level();
ServletRequestAttributesattributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
Optional.ofNullable(attributes).ifPresent(attribute-> {
HttpServletRequestrequest=attribute.getRequest();
request.getRequestURI();
request.getRemoteAddr();
logManage(logLevel, "Request uri [{}],remote addr {}", request.getRequestURI(), request.getRemoteAddr());
});
Object[] args=joinPoint.getArgs();
MethodSignaturemethodSignature= (MethodSignature) joinPoint.getSignature();
Methodmethod=methodSignature.getMethod();
logManage(logLevel, "In log method:[{}],args [{}]", method, args);
}
@AfterReturning(value="allRequestMethod()", returning="returnValue")
publicvoiddoAfter(JoinPointjoinPoint, ObjectreturnValue) {
if (!logEnabled) {
return;
}
AutoLogaroundLogger=getAutoLog(joinPoint);
if (!aroundLogger.outLog()) {
return;
}
AutoLogLevelEnumlogLevel=Objects.equals(aroundLogger.level(), NONE) ?loggingLevel : aroundLogger.level();
MethodSignaturemethodSignature= (MethodSignature) joinPoint.getSignature();
Methodmethod=methodSignature.getMethod();
logManage(logLevel, "Out log method:[{}],return [{}]", method, returnValue);
}
privateAutoLoggetAutoLog(JoinPointpoint) {
MethodSignaturemethodSignature= (MethodSignature) point.getSignature();
Methodmethod=methodSignature.getMethod();
AutoLogresult=method.getAnnotation(AutoLog.class);
if (Objects.isNull(result)) {
returnmethod.getDeclaringClass().getAnnotation(AutoLog.class);
}
returnresult;
}
privatevoidlogManage(AutoLogLevelEnumlevel, Stringmarket, Object... args) {
switch (level) {
caseWARN:
log.warn(market, args);
break;
caseDEBUG:
log.debug(market, args);
break;
default:
log.info(market, args);
}
}
}