Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Log for Rest Controller

I have a rest controller contains many methods

@RestController
@RequestMapping("v1/test")
public class TestRestController {

   ...... 100 methods (GET, POST, PATCH, etc)
}

How can I know which method is being accessed without using print in each method?
Are there any ways to do that?

like image 301
SpringKhmer Avatar asked Jan 31 '20 03:01

SpringKhmer


3 Answers

You can use Spring AOP:

package com.example;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class ExampleAspect {

    @Before("execution(* com.example.TestRestController(..)")
    public void log(JoinPoint joinPoint) {
        System.out.println("Executing :" + joinPoint.toString());
    }
}

like image 145
DiogoSantana Avatar answered Oct 20 '22 20:10

DiogoSantana


While you can use AOP tactics noted in the other answers to log the methods, there are better approaches if all you want to do is log all of the requests and responses for the endpoints those methods implement. There are a couple ways this can be done: Use Spring's CommonRequestLoggingFilter or write your own HandlerInterceptor. Here is a nice article on the first two options.

like image 2
rgoers Avatar answered Oct 20 '22 20:10

rgoers


Using Aspect Oriented Programming with Spring:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;    

@Aspect
public class SpringAspect {

    private static final Logger LOG = LoggerFactory.getLogger(SpringAspect.class);

    @Before("execution(* sample.package.path.TestRestController.*(..))")
    public void executedMethodsLogger(JoinPoint joinPoint) {
        LOG.info("[ Executed method {} ]", joinPoint.toString());
    }

}
like image 1
Anuradha Avatar answered Oct 20 '22 20:10

Anuradha