I've a Spring application that expose restful endpoints through @RequestMapping annotation in Controller classes.
I wish that were logged into the console, at server startup, all the endpoints of all the application's controller.
I use a tomcat server and log4j for logging.
Thanks.
Let’s say you want to log all the requests to your REST APIs developed using Spring Boot in a centralized way. You don’t want to add logs to each and every API. How to do that in Spring Boot? Using Spring Interceptors. But it is in straight forward to use it. STEP1 : Create a spring handler interceptor and log all incoming requests.
It is not recommended to expose the logs through the endpoint unless you do not have any other way of looking into the logs from your application. Spring Boot Actuator provides a way to expose your log files through the REST endpoint without any custom development.
Event Listener Approach For creating a REST API service, we use @RestController and @RequestMapping in the controller class. These classes register in the spring application context as a spring bean. Therefore, we can get the endpoints by using the event listener when the application context is ready at startup.
When using starters, Logback is used for logging by default. Spring Boot preconfigures it with patterns and ANSI colors to make the standard output more readable. Let's now run the application and visit the http://localhost:8080/ page, and see what happens in the console:
For those who use spring-boot:
In the latest spring-boot release (since v2.1), they changed the mapping default log level (as specified in the Release Notes here).
Add one of the following properties to application.properties file:
logging.level.web=TRACE
logging.level.org.springframework.web=TRACE
Sample Console Output:
2018-12-12 11:16:51.793 TRACE 11868 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping
c.n.c.MyController:
{POST /users}: addUser(User)
{DELETE /users}: deleteUser(User)
{PUT /users}: updateUser(User)
{GET /users/{id}}: getUserById(String)
{GET /users}: getUsers()
{GET /users_static}: getUsersStaticList()
2018-12-12 11:16:51.795 TRACE 11868 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping
o.s.b.a.w.s.e.BasicErrorController:
{ /error}: error(HttpServletRequest)
{ /error, produces [text/html]}: errorHtml(HttpServletRequest,HttpServletResponse)
Since Spring 5.3.5, it's possible to use a special dedicated hidden Logger for logging the endpoints mapping, without overhead of logging all requests processing.
<Logger name="_org.springframework.web.servlet.HandlerMapping.Mappings" level="debug" additivity = "false">
This feature was introduced in https://github.com/spring-projects/spring-framework/issues/26539
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With