先看效果:
Log.java
- 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 Log {
- System.Logger.Level level() default System.Logger.Level.DEBUG;
- String tag() default "";
- }
LogAspect.java
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.annotation.After;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.aspectj.lang.annotation.Pointcut;
- import org.aspectj.lang.reflect.MethodSignature;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.stereotype.Component;
- import java.util.Arrays;
- @Aspect
- @Component
- @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
- public class LogAspect {
- private long marker;
- private String className;
- private String methodName;
- private Log log;
- private Logger logger;
- @Pointcut("@annotation(tacos.util.Log)")
- public void logPointCut() {
- }
- private void doLog(Logger logger, System.Logger.Level level, String msg) {
- if (level == System.Logger.Level.DEBUG) {
- logger.debug(msg);
- } else if (level == System.Logger.Level.INFO) {
- logger.info(msg);
- } else if (level == System.Logger.Level.WARNING) {
- logger.warn(msg);
- } else if (level == System.Logger.Level.ERROR) {
- logger.error(msg);
- } else if (level == System.Logger.Level.TRACE) {
- logger.trace(msg);
- }
- }
- @Before("logPointCut()")
- public void before(JoinPoint joinPoint) {
- className = joinPoint.getTarget().getClass().getName();
- methodName = joinPoint.getSignature().getName();
- log = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(Log.class);
- logger = LoggerFactory.getLogger(className);
- String msg = String.format("%sCall open: %s.%s(%s) ", log.tag(), className, methodName, Arrays.toString(joinPoint.getArgs()));
- doLog(logger, log.level(), msg);
- marker = System.currentTimeMillis();
- }
- @After("logPointCut()")
- public void end(JoinPoint joinPoint) {
- doLog(logger, log.level(), String.format("%sCall done: %s.%s, duration: %d ms", log.tag(), className, methodName, (System.currentTimeMillis() - marker)));
- }
- }
使用:
在方法上使用注解即可:
- @Log(level = System.Logger.Level.ERROR, tag = "[OK] ")