Get Started Quickly With Spring Boot Logging
Get Started Quickly With Spring Boot Logging
blog
In the same vein as Get Started Quickly With Kotlin Logging and Getting Started Quickly With C# Logging articles, we’re headed across the coffee sh
While we’ve written already on the topic of Java logging in Get Started Quickly With Java Logging, the Spring Boot framework simpli es a lot of the p
Grab your Venti red-eye triple espresso with almond milk, and let’s get started!
Before we delve into logging and Spring Boot, we need a demo project to experiment with. The easiest way to get going with Spring Boot is to use th
Spring Initializr will give us a great UI for picking and choosing exactly what Spring components we want, as well as some other options.
For this article we’ll use Gradle for dependency management and to build our application. If you want to import the project into Eclipse or IntelliJ, f
The Spring Initializr website defaults to Maven for dependency management. Let’s change the “Project” choice from “Maven Project” to “Gradle Pro
Now there are just a couple more tweaks we need to make to be consistent with this article:
1. Choose “Java” as our “language.” Kotlin is also great but has a learning curve if you are unfamiliar with it.
2. In the “Dependencies” search box, enter Web and select the “Full-stack web development” option.
3. Next, change the “Artifact” text input from “demo” to “logging.” Now we’re good to go!
Check out the below screenshot to see all of the changes to make:
Once you’ve made the changes, click the “Generate Project” button to download an archive containing our project. After extracting the downloaded
If you’ve never used Gradle before, I highly recommend reading up on it as an alternative to Maven. It uses the same repositories as Maven, but its
This results in shorter and clearer build scripts than the verbose XML con gurations Maven uses. Life is too short to deal with XML if we don’t have t
Let’s test our current setup by building and running our application. In the console, run the following command from the root of our project folder:
$ ./gradlew bootRun
The initial build and project execution will take a few minutes while Gradle downloads dependencies. Once th
It is an error, but don’t worry, that is expected. For whatever reason, the projects created with Spring Initializr don’t include a default controller. Thi
To create a controller, under the src/main/java/com/example/logging folder, create a new le and name it LoggingController.java and insert the
package com.example.logging;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoggingController {
@RequestMapping("/")
public String index() {
return "Welcome to Spring Logging!";
}
}
If the application is still running, kill it by pressing Ctrl-C back in the console.
There isn’t any automatic reloading, so to see the result of our changes we need to stop and rerun the application. Once the application nishes res
You’ll see our welcome message indicating that we have a working project:
We now have a working controller to add our logging statements to. With our base setup done, let’s get to the heart of the article: adding logging.
Spring Boot comes with a precon gured default logger based on the Logback framework. We can use this logging setup out of the box without any a
The default logger is great for quick prototyping or experimenting. However, we’ll inevitably want a bit more con guration, which we’ll get to in later
First, to update our logging controller to use this built-in logger, update LoggingController.java to the following:
package com.example.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoggingController {
@RequestMapping("/")
public String index() {
logger.trace("This is a TRACE message.");
logger.debug("This is a DEBUG message.");
logger.info("This is an INFO message.");
logger.warn("This is a WARN message.");
logger.error("You guessed it, an ERROR message.");
return "Welcome to Spring Logging! Check the console to see the log messages.";
}
}
If you haven’t already, stop the current running application by pressing Ctrl-C again in the console. Then, run the updated application again:
$ ./gradlew bootRun
Once that nishes loading, look over at the console to see our log messages in all their glory:
Hmm… Looks like we’re only seeing the INFO, WARN, and ERROR log level messages, and not the TRACE and DEBUG messages.
If you’re at all familiar with Java logging, this probably won’t come as a surprise. The Spring Boot logger is con gured to only log messages of INFO
logging.level.root=WARN
logging.level.com.example=TRACE
Now rerun the application and refresh your browser. In the console output you’ll see our missing log statements:
We now have working code outputting log messages. Let’s move onto con guring Logback by creating a separate con guration le to override the d
With Spring Boot, it’s easy to enable color-coded output for your logging, if you’re using a terminal that supports ANSI. That way, readability can be
Log Level
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
We enable this by, again, editing our application.properties le. More speci cally, we’ll con gure the spring.output.ansi.enabled property.
The possible values for this property are three: ALWAYS, NEVER, and DETECT. The effect of ALWAYS and NEVER are pretty obvious: they enable and
spring.output.ansi.enabled=ALWAYS
Go back to the terminal. If the application is running, stop it with CTRL + C. Then, start it again by running $ ./gradlew bootRun. Finally, use your br
Though the colors you see above are the default ones, cccording to Spring Boot’s documentation, this is the complete list of colors and styles suppo
blue
cyan
faint
green
magenta
red
yellow
While we can con gure everything we need to for Logback in our application.properties le, this isn’t recommended, as this le is prone to be pollu
The recommended way in Spring is to store the Logback con guration in a separate le named logback-spring.xml. Spring will load this before any
Go ahead and create the logback-spring.xml le under src/main/resources in the same place as application.properties and drop the following in
<root level="info">
<appender-ref ref="Console" />
</root>
We won’t get into all the details of the Logback con guration here, but we are directing everything at TRACE level or higher (effectively logging ever
In short, we create a console log appender and set a custom message pattern. This controls the formatting of any messages being logged with it. O
That’s it for the Logback con guration. This con guration le is also where you can add any additional appenders or formatters. Refer to the Logbac
Now let’s swap out our Logback setup for our trusty logging library: Log4j2.
Spring Boot uses the SLF4J library under the hood to abstract its logging. This makes switching to Log4j2 relatively simple. It’s just a matter of addi
Since we started with the Spring Boot web starter, we currently have a transitive dependency on the Logback library. The Logback library comes in t
To use Log4j2, we need to rst exclude the Logback library. We’ll then include the Log4j2 library. Let’s update our Gradle build to make these chang
plugins {
id 'org.springframework.boot' version '2.1.8.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
plugins {
id 'org.springframework.boot' version '2.1.8.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
configurations.all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-log4j2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
In the updated build script, we’ve added an exclude group for the spring-boot-starter-logging module, which is where the Logback dependency co
We’ll con gure our Log4j2 logging to output the same message format used in our earlier Logback example. Let’s add a Log4j2 con guration le to o
Create the following named log4j2-spring.xml le in src/main/resources where our application.properties resides:
Why would we want to go through this extra setup to use Log4j2 when Logback is ready to go?
Being able to swap over to Log4j2 is handy, especially when moving from an existing project to Spring Boot. We can carry over our existing Log4j2 co
This is particularly useful when working with an existing and complex Log4j2 con guration. It’s common to have various appenders writing to multi
While Logback is considered the successor to Log4j2, Log4j2 is still used in many applications. If you’ve never used Logback before, check out the f
Keep in mind that, while recommended, it’s not obligatory to use Log4j2 through SLF4J. It’s totally possible to bypass SLFJ and use Log4j2 directly.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
The next—and last—change is in the code that instantiates the logger. You have to replace the following line:
That’s it! You’re now logging natively with Log4j2 without using SLF4J. So, what’s the point of that?
Well, SLF4J is a facade or abstraction for many logging frameworks. Its goal is to allow developers to easily and quickly change the logging framewo
That flexibility comes at a cost, though. The various logging frameworks—Log4j2, for instance—will often add valuable exclusive new features you m
At this point, you’ve successfully con gured Spring Boot to log with two different logging frameworks. We’ve also looked at how to add additional lo
Logging is paramount to successfully monitoring and troubleshooting applications. Don’t overlook security needs when adding logging to an applica
It’s important to ensure we aren’t logging sensitive information such as passwords or account details. Refer to the OWASP Logging Cheatsheet for a
And, with that, you should be all set to get started on your own with Spring Boot logging.
Then, once you have a solid understanding of the fundamentals of logging, it’s time to venture into deeper waters. You might want to start learning
Firstly, it can help an organization not only x problems but prevent them from happening altogether. In addition, logging can be a source of invalua
After bringing it to the surface, you can use it to inform your decision-making. And to be able to adopt those processes, you need a comprehensive
Like this article? Follow us on LinkedIn, Twitter, YouTube or Facebook to see the content we post.
Kafka Connectors: What Are They and How Can You Use Them?