Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
Spring Boot - Logging
Next article icon

Spring Boot - Logging

Last Updated : 02 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Logging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spring Boot offers flexible logging capabilities by providing various logging frameworks and also provides ways to manage and configure the logs.

Why to use Spring Boot - Logging?

A good logging infrastructure is necessary for any software project as it not only helps in understanding what's going on with the application but also to trace any unusual incident or error present in the project. This article covers several ways in which logging can be enabled in a spring boot project through easy and simple configurations. Let's first do the initial setup to explore each option in more depth.

Elements of Logging Framework

  • Logger: It captures the messages.
  • Formatter: It formats the messages which are captured by loggers.
  • Handler: It prints messages on the console, stores them in a file or sends an email, etc.

Java provides several logging frameworks, some of which are:

  1. Logback Configuration logging
  2. Log4j2 Configuration logging
  3. Logging with Lombok
  4. @Slf4j and @CommonsLog

Initial Setup

To create a simple Spring Boot project using Spring Initializer, please refer to this article . Let's define a simple Rest Controller that outputs various levels of log messages.

Java
// Rest Controller to print various log level messages package com.log.controller;  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 LogController {      // creating a logger     Logger logger         = LoggerFactory.getLogger(LogController.class);      @RequestMapping("/log") public String log()     {         // Logging various log level messages         logger.trace("Log level: TRACE");         logger.info("Log level: INFO");         logger.debug("Log level: DEBUG");         logger.error("Log level: ERROR");         logger.warn("Log level: WARN");          return "Hey! You can check the output in the logs";     } } 

Now we simply need to run the application and hit http://localhost:8080/log to see the log messages.

Log Levels

Levels

Usage

Error

It is used for non-recoverable error.

Warning

It is used for recoverable error.

Info

It is used for audit purpose.

Debug

It is used for investigation.

Trace

It is used for detailed investigation.

0. Default Logging With No Configurations

Spring boot allows us to see the logs in the console even if we do not provide any specific configuration for it. This is because spring boot uses Logback for its default logging. Spring boot's internal logging provider is A pache Commons which provides support for Java Util Logging , Log4j2 , and Logback . Hence Apache Commons had to be manually imported until spring boot 1.x. However, since spring boot 2.x, it is downloaded transitively. To be more specific, Spring boot starters such as spring-boot-starter-web imports spring-boot-starter-logging which automatically pulls in Logback. On running the application and visiting the http://localhost:8080/log page, we can see the following output in the console:

Output_screen

The log format and ANSI colors are configured By Spring Boot beforehand to make the logging more readable. The following components are present in the log output:

Log_output
  1. Date of logging
  2. Time with millisecond precision
  3. Log level shows INFO, WARN and ERROR by default
  4. Process ID
  5. --- acts as a separator
  6. Name of the thread enclosed in square brackets
  7. Name of the logger that shows source class name
  8. The log message

Console Output

The log levels supported by Spring boot are TRACE , INFO , DEBUG , ERROR , and WARN . By default ERROR, INFO and WARN are printed to the console. It is possible to activate the debug and trace level by starting the application with --debug flag or --trace flag as follows:

java -jar target/log-0.0.1-SNAPSHOT.jar --debug
java -jar target/log-0.0.1-SNAPSHOT.jar --trace

Alternatively, This can also be done by adding the following properties in the application.properties file.

debug=true
trace=true

Color-Coded Output

If ANSI is supported by your terminal then color-coded log output can be seen in the console. The following property can be set in the application.properties file to get the color-coded output:

spring.output.ansi.enabled=always

Logging to a file

Spring boot only logs to the console by default. In order to log into a file, the following properties need to be added to the application.properties file:

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

After adding these properties if we run the spring boot application and visit the page http://localhost:8080/log , we can see logs on the console as well as in the log file. A new folder by the name logs is created in the current path and inside this folder is the log file called application.log. The content of the log file is as follows:

Content_of_log_file

1. Logging with Logback configuration

Spring boot enables logback to be configured in a specific manner to meet our project's requirements. In order to do so, we need to define a configuration file where we can specify logging pattern, color, different properties for file logging & console logging, and an efficient rolling policy to prevent the creation of huge log files. Whenever Spring boot finds a file with any of the following names, It automatically overrides the default configuration.

  • logback-spring.groovy
  • logback.groovy
  • logback-spring.xml
  • logback.xml

Now let's create a simple logback-spring.xml file

XML
<?xml version="1.0" encoding="UTF-8"?> <configuration>      <!-- Setting up log path and log file name -->     <property name="LOG_PATH" value="./logs" />     <property name="LOG_FILE_NAME" value="application_logback" />      <!-- Setting up logging pattern for console logging -->     <appender name="ConsoleOutput"         class="ch.qos.logback.core.ConsoleAppender">         <layout class="ch.qos.logback.classic.PatternLayout">             <Pattern>                 %white(%d{ISO8601}) %highlight(%-5level) [%yellow(%t)] : %msg%n%throwable             </Pattern>         </layout>     </appender>      <!-- Setting the filename and logging pattern for log file -->     <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{yyyy-MM-dd HH:mm:ss} [%thread] %-5level : %msg%n             </Pattern>         </encoder>                <!-- Setting up a rolling policy with rolling done               daily and when file size is 10MB-->         <rollingPolicy             class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">             <fileNamePattern>${LOG_PATH}/archived/${LOG_FILE_NAME}-%d{yyyy-MM-dd}.%i.log             </fileNamePattern>             <timeBasedFileNamingAndTriggeringPolicy                 class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">                 <maxFileSize>10MB</maxFileSize>             </timeBasedFileNamingAndTriggeringPolicy>         </rollingPolicy>     </appender>      <!-- Logging at INFO level -->     <root level="info">         <appender-ref ref="LogFile" />         <appender-ref ref="ConsoleOutput" />     </root>          <!-- Logging at TRACE level -->      <logger name="com.log" level="trace" additivity="false">         <appender-ref ref="LogFile" />         <appender-ref ref="ConsoleOutput" />     </logger>      </configuration> 


On running the application, and visiting the page http://localhost:8080/log, we receive the following console output:

Console_output

The console output is as per the logging pattern and color defined in the logback-spring.xml file. A new log file by the name application-logback.log is created in the/logs folder present in the current path which gets archived through a rolling policy. The log file output is as follows:

Log_file_output

2. Logging with Log4j2 configuration

For using log4j2, we need to exclude Logback from our starter dependency and add the dependency for log4j2 as follows:

XML
<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId>     <exclusions>         <exclusion>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-logging</artifactId>         </exclusion>     </exclusions> </dependency> <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> 

Next, we need to define the configuration file for Log4j2. When spring boot finds a file with any of the following names, It automatically overrides it over default configuration.

  • log4j2-spring.xml
  • log4j2.xml

Now let's create a simple log4j2-spring.xml file as follows:

XML
<?xml version="1.0" encoding="UTF-8"?>  <Configuration>      <!-- Setting up log path and log file name -->     <Properties>      <property name="LOG_PATH" value="./logs" />     <property name="LOG_FILE_NAME" value="application-log4j2" />     </Properties>          <!-- Setting up logging pattern for console logging -->     <Appenders>         <Console name="ConsoleOutput" target="SYSTEM_OUT">             <PatternLayout                 pattern="%style{%d{ISO8601}}{white} %highlight{%-5level} [%style{%t}{bright,yellow}] : %msg%n%throwable"                 disableAnsi="false" />         </Console>          <!-- Setting the filename and logging pattern for log file. Also setting               up a rolling policy with rolling done daily and when file size is 10MB -->         <RollingFile name="LogFile"             fileName="${LOG_PATH}/${LOG_FILE_NAME}.log"             filePattern="${LOG_PATH}/$${date:yyyy-MM}/application-log4j2-%d{dd-MMMM-yyyy}-%i.log.gz">             <PatternLayout>                 <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level : %msg%n                 </pattern>             </PatternLayout>             <Policies>                 <OnStartupTriggeringPolicy />                 <SizeBasedTriggeringPolicy size="10 MB" />                 <TimeBasedTriggeringPolicy />             </Policies>         </RollingFile>     </Appenders>      <Loggers>                <!-- Logging at INFO level -->         <Root level="info">             <AppenderRef ref="ConsoleOutput" />             <AppenderRef ref="LogFile" />         </Root>          <!-- Logging at TRACE level -->         <logger name="com.log" level="trace" additivity="false">             <appender-ref ref="LogFile" />             <appender-ref ref="ConsoleOutput" />         </logger>      </Loggers>  </Configuration> 


On running the application, and visiting the page http://localhost:8080/log , we receive the following console output:

Console_output

The console output is as per the logging pattern and color defined in the logback-Log4j2.xml file. A new log file by the name application-Log4j2.log is created in the/logs folder present in the current path which gets archived through a rolling policy. The log file output is as follows:

log_file_output

3. Logging with Lombok

Lombok in Jav is a library tool which is used to minimize the boilerplate code like getters, setters, toString methods, constructors etc. For logging, we have to declare the instance of a logger. For this we can use lombok for avoiding the boilerplate code and can use various annotations of lombok.

To work with lombok, we need to add dependency in our xml configuration.

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>

4. @Slf4j and @CommonsLog

To change the logging framework without impacting the code we can use @Slf4j and @CommonsLog logging API annotations. These annotations adds the logger instances in the class path.

Note: For @Slf4j: org.slf4j.Logger
For @CommonsLog: org.apache.commons.logging.Log

Java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import lombok.extern.slf4j.Slf4j;  @Slf4j public class Main {      public static void main(String args[]) {     log.info("Info level");     log.error("Error level");   } } 

In the above code, we have added an annotation @Slf4j . This annotation will automatically add the field named log.


Next Article
Spring Boot - Logging

A

akankshapatro
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Advance Java
  • Geeks-Premier-League-2022
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Consume Message Through Kafka, Save into ElasticSearch, and Plot into Grafana
    In this article, we are going to make a program to produce some data using Kafka Producer which will consume by the Kafka Consumer and save into the elastic search DB, and later on, plot that JSON data into the Grafana dashboard. Start with configuring all the required software and tool. Requirement
    7 min read
    How to Implement AOP in Spring Boot Application?
    AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of
    10 min read
    Spring Boot - AOP(Aspect Oriented Programming)
    The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the e
    4 min read
    Spring Boot - Cache Provider
    The Spring Framework provides support for transparently adding caching to an application. The Cache provider gives authorization to programmers to configure cache explicitly in an application. It incorporates various cache providers such as EhCache, Redis, Guava, Caffeine, etc. It keeps frequently a
    6 min read
    Spring Boot - AOP Around Advice
    Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transa
    6 min read
    Spring Boot - Auto-configuration
    Spring Boot is heavily attracting developers toward it because of three main features as follows: Auto-configuration - such as checking for the dependencies, the presence of certain classes in the classpath, the existence of a bean, or the activation of some property.An opinionated approach to confi
    5 min read
    Spring Boot - EhCaching
    EhCache is an open-source and Java-based cache. It is used to boost performance. Its current version is 3. EhCache provides the implementation of the JSR-107 cache manager. Features of EhCache are given below: It is fast, lightweight, Flexible, and Scalable.It allows us to perform Serializable and O
    5 min read
    Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    3 min read
    Spring Boot - Starter Test
    Spring Boot is built on top of the spring and contains all the features of spring. It is becoming a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration and setup.
    5 min read
    Exception Handling in Spring Boot
    Exception handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences