Logging Method Entry/Exit in Spring Boot

December 1, 2019

I wanted to log (using slf4j) to a log file at the start and end of each service method in my Spring Boot project. This can be done by adding the following class to the project.

Note that the @Around annotation defines which package contains the methods that are wrapped.

package com.drumcoder.diary;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * <h1>ServiceTelemetryLogger</h1>
 * ServiceTelemetryLogger logs telemetry for all methods for the service hierarchy at info level.
 * Modifying the logging level to info will switch the telemetry on for all classes under
 * com.drumcoder.diary.service.
 */
@Aspect
@Component
public class ServiceTelemetryLogger {
    private static final Logger LOGGER = LoggerFactory.getLogger("com.drumcoder.ServiceTelemetryLogger");

    /**
     * <h>logBeforeAndAfterServiceMethods</h>
     * Adds trace logging before a proceeding join point method call.
     * @param pjp The proceeding joint point
     * @return Result of method call
     * @throws Throwable
     */
    @Around("execution(* com.drumcoder.diary.service..*.* (..))")
    public Object logBeforeAndAfterServiceMethods(ProceedingJoinPoint pjp) throws Throwable {
        LOGGER.info("{} has started execution.", pjp.getSignature());
        Object resultOfMethodCall = pjp.proceed();
        LOGGER.info("{} finished execution", pjp.getSignature());
        return resultOfMethodCall;
    }
}

I also needed to enable AspectJ for this to work, so the following class was also added

package com.drumcoder.diary.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
public class AspectjConfig {

}