Pages

Logging in Spring

Spring has been designed to use the Apache Commons Logging, often called JCL from its previous name, Jakarta Commons Logging. It acts as a wrapper (more technically, bridge) hiding the actual log library used by the application. By default, Logback is assumed.

JCL provides six level of logging, from trace to fatal. To show how it works, I have modified the greeting method from my simple Web Service I am playing with:
private static final Log log = LogFactory.getLog(GreetingController.class);

public String greeting() {
 log.trace("trace hello");
 log.debug("debug hello");
 log.info("info hello");
 log.warn("warn hello");
 log.error("error hello");
 log.fatal("fatal hello");
 return "Hello";
}
LogFactory is the apache.commons.logging class that acts as a factory to create a log object.

If I consume the service, I get something like this:
I see some logging in the console window generated by my app, with a couple of surprises. I miss trace and debug messages, and the fatal one is showed as a plain error.

The latter is a feature, not a bug. Since Logback has no fatal level, JCL maps a fatal request to the error level.
The first one is the default behaviour common to many loggers. If I don't specify which level of logging I want to display, only messages from info level onward are shown.
Here I want to see the full logging, so I add this line to the Spring application.properties file:
logging.level.dd.manny=trace
I restart my Spring application, consume the service, and I get the expected changes in the log.

Log to file

By default, when I ask Spring to log to file, it sends the messages to a file named spring.log, it is usually a good idea to keep this name, however it make sense to place this file in a specific folder. To do that, I add this line to the Spring properties file:
logging.path=/tmp
Last thing. I want to log _only_ to file. To do that I have to mess a bit with the actual logger (once again, in this case Logbackis assumed) configuration file. I am simply using the default one provided by Spring, specifying FILE as appender in the root element:
<root level="INFO">
 <appender-ref ref="FILE" />
</root>
Only the Spring banner is printed to standard output, the log goes straight to file.

The full Spring Boot project is on github. The relevant files are GreetingController.java, application.properties, and logback.xml.

No comments:

Post a Comment