Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Get Started Quickly With Spring Boot Logging

- The document discusses configuring logging in a Spring Boot application. It begins by creating a sample Spring Boot project using Spring Initializr and Gradle. - Next, it demonstrates using the default Spring Boot logger by adding logging statements to a sample controller class. This only outputs INFO and higher level logs. - Then it shows how to configure the logging level in application.properties to output TRACE and DEBUG logs. Finally, it enables colored console output for logs and discusses creating a custom Logback configuration file.

Uploaded by

Rocky9949
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Get Started Quickly With Spring Boot Logging

- The document discusses configuring logging in a Spring Boot application. It begins by creating a sample Spring Boot project using Spring Initializr and Gradle. - Next, it demonstrates using the default Spring Boot logger by adding logging statements to a sample controller class. This only outputs INFO and higher level logs. - Then it shows how to configure the logging level in application.properties to output TRACE and DEBUG logs. Finally, it enables colored console output for logs and discusses creating a custom Logback configuration file.

Uploaded by

Rocky9949
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

GET A DEMO

blog

Get Started Quickly With Spring Boot


Logging
February 10, 2021
by SentinelOne

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

Create a Spring Boot starter/blog/get-started-quickly-with-java-logging/ project

Use Gradle to build our application


Con gure the default Spring Boot logger
Use Log4j2 with Spring Boot

Customize the logging con gurations

Grab your Venti red-eye triple espresso with almond milk, and let’s get started!

Create a Spring Boot Test Project

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

Building the Spring Boot Starter Project

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

2021-02-04 13:35:25.265 INFO 3744 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initiali


2021-02-04 13:35:25.266 INFO 3744 --- [ main] o.s.web.context.ContextLoader : Root Web
2021-02-04 13:35:25.475 INFO 3744 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initiali
2021-02-04 13:35:25.660 INFO 3744 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat s
2021-02-04 13:35:25.663 INFO 3744 --- [ main] com.example.logging.LoggingApplication : Started

Open a browser and enter http://localhost:8080 to see our application:

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

Let’s x that by adding a controller.

Fixing the Spring Boot Starter Project

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.

Using the Default Spring Boot Logger

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 {

Logger logger = LoggerFactory.getLogger(LoggingController.class);

@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

Refresh your browser, and you’ll see our wonderful message:

Once that nishes loading, look over at the console to see our log messages in all their glory:

2021-02-04 13:43:11.939 INFO 12880 --- [nio-8080-exec-1] com.example.logging.LoggingController : This is


2021-02-04 13:43:11.939 WARN 12880 --- [nio-8080-exec-1] com.example.logging.LoggingController : This is
2021-02-04 13:43:11.939 ERROR 12880 --- [nio-8080-exec-1] com.example.logging.LoggingController : You gue

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:

2021-02-04 13:45:51.932 TRACE 1140 --- [nio-8080-exec-1] com.example.logging.LoggingController : This is


2021-02-04 13:45:51.932 DEBUG 1140 --- [nio-8080-exec-1] com.example.logging.LoggingController : This is
2021-02-04 13:45:51.932 INFO 1140 --- [nio-8080-exec-1] com.example.logging.LoggingController : This is
2021-02-04 13:45:51.932 WARN 1140 --- [nio-8080-exec-1] com.example.logging.LoggingController : This is
2021-02-04 13:45:51.932 ERROR 1140 --- [nio-8080-exec-1] com.example.logging.LoggingController : You gues

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

Enabling Color-Coded Output

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

Create a Custom Logback Configuration

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

<?xml version="1.0" encoding="UTF-8"?>


<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>

<root level="info">
<appender-ref ref="Console" />
</root>

<!-- Log everything at the TRACE level -->


<logger name="com.example" level="trace" additivity="false">
<appender-ref ref="Console" />
</logger>
</configuration>

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

2021-02-04 20:49:17 [http-nio-8080-exec-1] TRACE c.example.logging.LoggingController - This is a TRACE messa


2021-02-04 20:49:17 [http-nio-8080-exec-1] DEBUG c.example.logging.LoggingController - This is a DEBUG messa
2021-02-04 20:49:17 [http-nio-8080-exec-1] INFO c.example.logging.LoggingController - This is an INFO messa
2021-02-04 20:49:17 [http-nio-8080-exec-1] WARN c.example.logging.LoggingController - This is a WARN messag
2021-02-04 20:49:17 [http-nio-8080-exec-1] ERROR c.example.logging.LoggingController - You guessed it, an ER

This message pattern uses the following Logback variables:

%d{yyyy-MM-dd HH:mm:ss}—Date in the speci ed format

[%thread] —Current thread identi er writing the message


%-5level —The message level with ve-character, xed-width spacing
%logger{36} —The name of the logger writing the message
%msg%n —The actual message followed by a new line

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.

Configure Log4j2 for Logging

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

Currently, our Gradle build le, build.gradle, looks like this:

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'
}

Replace the contents of build.gradle with this:

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:

<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="Console" target="SYS


While this looks very similar to the Logback example, there are a few minor differences. Running our applica

[log4j] 2021-02-04 21:02:04 [http-nio-8080-exec-1] TRACE com.example.logging.LoggingController - This is a T

We’ve now successfully swapped out Logback for Log4j2.

Why Use Log4j2 Instead of Logback?

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

Using Log4J2 Without SLF4J

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.

First, we have to change the imports. Remove the following lines:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

And replace them with these ones:

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:

Logger logger = LoggerFactory.getLogger(LoggingController.class);

With this one:

Logger logger = LogManager.getLogger(LoggingController.class);

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

The End of Our Logging Journey

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.

The Next Step


What should your next steps be? Firstly, keep reading and practicing. There’s a lot to learn about logging. From the main best practices to how to ke

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.

Read more about Cyber Security

Kafka Connectors: What Are They and How Can You Use Them?

©2023 SentinelOne, All Rights Reserved.


Privacy Policy Master Subscription Agreement

You might also like