AI Hints
Home›Spring Boot Tutorial›YAML, Profiles and Logging
Spring Boot · Lesson 42 of 120

Logging

Messages from your app.

⏱ 2 min read▶ Video at 55:43🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Print line is fine for quick tests. But real apps use a logger. It adds a level to each message, and lets you choose how much to see.

  • println for quick tests
  • Real apps use a logger
  • Levels and control

Log levels

There are five levels, from most detail to most serious. Trace and debug are for developers, while fixing problems. Info is for normal events. Warn means something odd happened. And error means something failed. By default, Spring Boot shows info and above.

LevelUse for
TRACEtiny details
DEBUGdetails while fixing bugs
INFOnormal events (default)
WARNsomething odd
ERRORsomething failed

Using a logger

We create one logger per class, with Logger Factory. Log debug, info, and warn write messages at each level. Curly braces are placeholders, filled by the values after the message. In the properties file, we set our package to debug level. Run it. Book two logs a debug line, and an info line. Book nine logs a warning.

BookController.javajava
@RestController
public class BookController {

    private static final Logger log = LoggerFactory.getLogger(BookController.class);

    @GetMapping("/books/{id}")
    public String book(@PathVariable int id) {
        log.debug("Looking up book {}", id);
        if (id > 3) {
            log.warn("Someone asked for book {}, which doesn't exist", id);
            return "Not found";
        }
        log.info("Found book {}", id);
        return "Book " + id;
    }
}
Output
$ curl localhost:8080/books/2
Book 2
$ curl localhost:8080/books/9
Not found

── app log ──
DEBUG BookController : Looking up book 2
INFO  BookController : Found book 2
DEBUG BookController : Looking up book 9
WARN  BookController : Someone asked for book 9, which doesn't exist
Also uses application.properties
logging.level.com.example.bookshop=DEBUG
Also uses _curl.sh
curl localhost:8080/books/2
curl localhost:8080/books/9

Logging settings

Logging level, then a package name, sets the level for that package. Logging level root sets it for everything. And logging file name, also writes the log to a file. In production, info is usually right, and debug is for hunting bugs.

keyvalue
logging.level.com.example=DEBUGour package
logging.level.root=WARNeverything
logging.file.name=app.logalso to a file
ProductionINFO

Summary

Use a logger, not print line. Choose the level, from trace to error, per package, in your settings. Next, Command Line Runner.

Key takeaways
  • LoggerFactory.getLogger
  • debug, info, warn, error
  • logging.level.*
Next up: CommandLineRunner — code at startup