统一日志处理
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
String module() default "";
}
处理
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.util.StringUtils;
@Aspect
@Component
public class LogAdvice {
@Autowired
private SysLogService logService;
@Around(value = "@annotation(com.wuxian.annotation.LogAnnotation)")
public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
SysLogs sysLogs = new SysLogs();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
System.out.println(1);
String module = null;
LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
module = logAnnotation.module();
if (StringUtils.isEmpty(module)) {
ApiOperation apiOperation = methodSignature.getMethod().getDeclaredAnnotation(ApiOperation.class);
if (apiOperation != null) {
module = apiOperation.value();
}
}
if (StringUtils.isEmpty(module)) {
throw new RuntimeException("没有指定日志module");
}
sysLogs.setModule(module);
try {
Object object = joinPoint.proceed();
sysLogs.setFlag(true);
logService.save(sysLogs);
return object;
} catch (Exception e) {
sysLogs.setFlag(false);
sysLogs.setRemark(e.getMessage());
logService.save(sysLogs);
throw e;
}
}
}
使用
@RestController
@RequestMapping("/humiditys")
public class HumidityController {
@LogAnnotation
@ApiOperation(value = "湿度")
@PostMapping("/switch/{alert_value}")
public ResponseInfo switchHumidity(@PathVariable Long alert_value) {
}
}