Logging in Play Framework

Posted by Jean Arnaud on Wednesday, October 23, 2024

Logging with Play framework

The logging API is described in the official Play framework doc pages about Java logging and logger settings.

Let see how we can use it in an actual project.

Configuration

Lombok dependency

To use the @Slf4j annotation, you need to add the Lombok dependency to your project. Add to build.sbt:

libraryDependencies += "org.projectlombok" % "lombok" % "1.18.34"

logback config

Modify logback.xml to configure the logger pattern. You can specify a log level for each package and even classes, for example:

    <logger name="play" level="INFO" />
    <logger name="application" level="DEBUG" />
    <logger name="controllers" level="DEBUG" />
    <logger name="controllers.HomeController" level="WARN" />
    <logger name="db" level="DEBUG" />   
    <logger name="services" level="DEBUG" />

Usage

Let’s use the logger by annotating the HomeController and using the log:

@Slf4j
public class HomeController extends Controller {

    public Result index() {
        log.debug("Rendering index page");
        return ok(views.html.index.render());
    }
}

Running the app locally (sbt run) and accessing http://localhost:9000/ will display the page and the logs will contain:

DEBUG c.HomeController - Rendering index page

Conclusion

In this article we saw how to set up, configure and use the logging system in a Play Framework application.

A full project containing the code samples seen above can be used freely here: https://github.com/jarnaud/play-demo


comments powered by Disqus