[Java] Create custom logging aspect with Springboot AOP

Aspect-oriented Programming (AOP) enable developer design application with more “module-ize”. This example will show how to use AOP to log method execution in SpringBoot AOP.

Steps

  1. Add SpringBoot AOP dependency;
    In build.gradle, add dependency as below.

    dependencies {
       compile 'org.springframework.boot:spring-boot-starter-aop'
    }
  2. Enable AOP in SpringBoot application;
    In application.java, alter code as below.

    @EnableAspectJAutoProxy
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

    Adding annotation @EnableAspectJAutoProxy to enable springboot  AOP.

  3. Create logging aspect.
    Create file name loggingAspect.java and input code as below.

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    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.stereotype.Component;
    import org.springframework.util.StopWatch;
    
    @Aspect
    @Component
    public class LoggingAspect {
        private static final Logger logger= LogManager.getLogger(LoggingAspect.class);
    
        private static final int LOG_LEVEL_WARNING_THRESHOLD =5000;
    
        @Around("execution(* com.test..*(..)) && !execution(* com.test.controllers.advices.ApiResponseEntityExceptionHandler..*(..)) && !execution(* org.jooq..*(..))")
        public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    
            // Get intercepted method details
            String className = methodSignature.getDeclaringType().getSimpleName();
            String methodName = methodSignature.getName();
            String methodFullName=className+"."+methodName;
    
            final StopWatch stopWatch = new StopWatch();
    
            // Initial log when method start execute.
            logger.info(methodFullName+" started.");
            logParameterValue(proceedingJoinPoint);
    
            / /Measure method execution time.
            stopWatch.start();
            Object result = proceedingJoinPoint.proceed();
            stopWatch.stop();
    
            // Check with execution time, decide its logging level.
            long processTimeMillis=stopWatch.getTotalTimeMillis();
            String message="Execution time of " + methodFullName + "(): " + processTimeMillis + " ms.";
            if(processTimeMillis>= LOG_LEVEL_WARNING_THRESHOLD)
                logger.warn(message);
            else
                logger.info(message);
            return result;
        }
    
        private void logParameterValue(ProceedingJoinPoint proceedingJoinPoint) throws JsonProcessingException {
            MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
            Object[] arguments = proceedingJoinPoint.getArgs();
            String[] parameterNames = methodSignature.getParameterNames();
            if ((parameterNames != null) && (arguments!=null)) {
                for (int i = 0; i < parameterNames.length; i++) {
                    Object parameterValue = arguments[i];
                    String serializeValue = new ObjectMapper().writeValueAsString(parameterValue);
                    logger.debug("Parameter " + parameterNames[i] + " value: " + serializeValue);
                }
            }
        }
    }

     

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.