Senior
You need to implement custom logging for all incoming and outgoing requests to controllers. How would you do this?
sobes.tech AI
Answer from AI
To implement custom logging of all incoming and outgoing requests on controllers in Java, you can use aspect-oriented programming (AOP) with Spring AOP or AspectJ.
Example using Spring AOP:
@Aspect
@Component
public class LoggingAspect {
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void controllerMethods() {}
@Around("controllerMethods()")
public Object logRequests(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
// Log incoming request
System.out.println("Incoming request: " + request.getMethod() + " " + request.getRequestURI());
Object response = joinPoint.proceed();
// Log outgoing response
System.out.println("Outgoing response: " + response);
return response;
}
}
This aspect intercepts all methods in controllers, logs request and response information. Logging can be extended to include headers, request and response bodies, execution time, etc.