Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Logging with Spring Boot

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Spring Boot in Java helps in using Java-based frameworks to build web applications and microservices. It is an open-source tool. It uses Java, one of the most popular programming languages for application development. It makes it simple to make Spring-based applications that can be run quickly.

logging with spring boot

In this article, we will study Logging with Spring Boot.

What is Logging with Spring Boot?

Logging means noting down the points of development so that anyone can understand what happened in what phase of the development cycle. If you use Spring Boot for your application, you can enable logging quickly to get your points noted easily.

Log Format

The following are the parts of the logs in Spring Boot:-

  • Date and Time of the log.
     
  • Log Levels: WARN, INFO, DEBUG, ERROR, etc.
     
  • Process ID
     
  • Thread Name in square brackets.
     
  • Logger Name shows the source class name.
     
  • Log Message

 

Now, let us see some implementations of Logging with Spring Boot.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example with slf4j logger

First, we initialize a Spring-based application using the Spring Initializr in Maven Project, Java language, and Spring Web dependency.

Then, we create a class named HomeController.java inside our project’s folder in our Java folder. It will serve the purpose of RestController for our project. The code of our HomeController.java is as follows:

  • Java

Java

package com.example.demo;

import org.slf4j.ILoggerFactory;
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 HomeController {
Logger logger=LoggerFactory.getLogger(HomeController.class);
@RequestMapping("/")
public String hello(){
logger.trace("Home Controller trace accessed");
logger.error("Home Controller error accessed");
logger.debug("Home Controller debug accessed");
logger.info("Home Controller info accessed");
return "Hey there";
}
}

 

We can see that the file returns Hey there as the main output of the webpage. Furthermore, we see four logs each time the webpage loads: trace, error, debug, and info. We import the necessary files and use the LoggerFactory.getlogger() method to use the custom logging methods.

Also, the following program is to be written in the application.properties file to allow the logging methods to function. Without it, trace and debug may not work. Thus, we are specifying our log levels for our project.

logging.level.com.example=TRACE

 

OUTPUT

Upon running the application, the following is the output of the webpage:

webpage output

Below is the output for the logs printed in the console:

logs console output

We can see that all the logs have been duly noted. It serves our purpose of logging with Spring Boot.

Also, by default, logs are shown in the console. If we want To print them in a file, the following commands can be written in the application.properties file:

logging.file.path=logs/
logging.file.name=logs/application.log

Example with logback.xml

Apart from usually coding our logging methods in the RestController, we can create a log-back file to serve our purpose for Logging with Spring Boot. It can be named: logback.xml or logback-spring.xml.

Following is the program written in our logback.xml file in our resources folder inside our main folder in the src folder:

  • XML

XML

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

<property name="LOG_PATH" value="./logs" />
<property name="LOG_FILE_NAME" value="app_log_back" />

<appender name="ConsoleOutput"
class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%yellow(%d{ISO8601}) %highlight(%-5level) [%white(%t)] : %msg%n%throwable
</Pattern>
</layout>
</appender>

<appender name="LogFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/${LOG_FILE_NAME}.log</file>
<encoder
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{dd-MM-yyyy HH:mm:ss} [%thread] %-5level : %msg%n
</Pattern>
</encoder>


<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/archived/${LOG_FILE_NAME}-%d{dd-MM-yyyy}.%i.log
</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>5MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>

<root level="info">
<appender-ref ref="LogFile" />
<appender-ref ref="ConsoleOutput" />
</root>

<logger name="com.log" level="trace" additivity="false">
<appender-ref ref="LogFile" />
<appender-ref ref="ConsoleOutput" />
</logger>

</configuration>

 

We specify a printing pattern for our logs with colors as yellow for date and time and white for our log messages. Also, we set the format of our date and time formats. And we give the name to our logs file as app_log_back.log. We also print in on the console.

OUTPUT
Upon writing this file, we see the following output on the console:

logback.xml console output

We see that the app_log_back.log file is created in the Logs folder in our project with the following output:

logback.xml logs file output

Frequently Asked Questions

What is Spring Boot?

Spring Boot in Java helps in using Java-based frameworks to build web applications and microservices. It is an open-source tool. It uses Java, one of the most popular programming languages for application development. It makes it simple to make Spring-based applications that can be run quickly.

What do you mean by Logging with Spring Boot?

Logging means noting down the points of development so that anyone can understand what happened in what phase of the development cycle. If you use Spring Boot for your application, you can enable logging quickly to get your points noted easily.

What are the different components of a log in Spring Boot?

The following are the parts of the logs in Spring Boot: Date and Time, Log Level(WARN, ERROR, etc.), Process ID, Thread Name, Logger Name, and the Log Message. The — is the separator between them.

Conclusion

Spring Boot is an essential tool that helps develop various applications using Java programming language. Also, having a clear and concise logging infrastructure for your project is vital to keep track of the events happening. In this article, we studied Logging with Spring Boot. We started with its definition and components, then two ways to achieve Logging with Spring Boot.

We recommend you read the following articles too:-

You can also consider our Spring Boot Course to give your career an edge over others.

Happy Coding!

Topics covered
1.
Introduction
2.
What is Logging with Spring Boot?
2.1.
Log Format
3.
Example with slf4j logger
3.1.
Java
4.
Example with logback.xml
4.1.
XML
5.
Frequently Asked Questions
5.1.
What is Spring Boot?
5.2.
What do you mean by Logging with Spring Boot?
5.3.
What are the different components of a log in Spring Boot?
6.
Conclusion