Romper
Romper

Reputation: 2259

Spring log request payload

I want to log every incoming request data and payload(body). How to configure that in Spring Boot? And how to hide sensitive data like password in logs?

Is it possible to log the original 'raw' request body (e.g. JSON)?

Upvotes: 1

Views: 1988

Answers (2)

cralfaro
cralfaro

Reputation: 5948

You could use AOP (Aspect Oriented programming) and intercept all the requests and log the info you need. Also you can filter which kind of requests need to log. An example with Spring-Boot could be this code

If you want to skip some methods from the logging in the aspect you can add this:

Create an annotation

@Retention(RetentionPolicy.RUNTIME)
public @interface NoLogging {}


@Aspect
@Component
public class LogsAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventAspect.class);

    @Before("execution(* com.your.controller..*Controller.*(..)) && !@annotation(NoLogging)")
    public void beforeController(JoinPoint joinPoint){
        String packageName = joinPoint.getSignature().getDeclaringTypeName();
        String params = getArguments(joinPoint);
        String methodName = joinPoint.getSignature().getName();
        //Log here your message as you prefer
    }
}

And in any method from your Controllers, if you want to avoid the logging by aspects add the annotation

@RequestMapping(value = "/login", method = RequestMethod.GET)
@NoLogging
public ModelAndView loginUser(){
    //actions
}

Upvotes: 1

SangDang
SangDang

Reputation: 11

IMO, to log any incoming request should place at webserver level instead of application level. For example, you could turn on/off access_log at Nginx.

Upvotes: 0

Related Questions