Sobes.tech
Senior

How to add logging to all methods of the old service without changing the business logic?

sobes.tech AI

Answer from AI

To add logging to all methods of an old service without changing the business logic, aspect-oriented programming (AOP) can be used. In Java, this is often implemented using Spring AOP or AspectJ.

The main idea is to write an aspect that intercepts method calls and adds logging before and after the method execution.

Example using Spring AOP:

@Aspect
@Component
public class LoggingAspect {

    @Around("execution(* com.example.service..*(..))")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().toShortString();
        System.out.println("Method call: " + methodName);
        Object result = joinPoint.proceed();
        System.out.println("Method completed: " + methodName);
        return result;
    }
}

This approach allows adding logging without modifying the original code of the service methods. If the project does not use Spring, AspectJ with compile-time weaving or proxy objects can be considered.

If AOP is unavailable, dynamic proxies or libraries like ByteBuddy or Javassist can be used to inject logging at runtime.