Logger In Spring Boot java Logging Spring Spring Boot by devs5003 - August 15, 2023February 15, 20241 Last Updated on February 15th, 2024We often pay very less attention on the implementation of logging during the development phase of an application. On the other hand, it becomes mandatory when we deploy the application in production. Sometimes we just insert ‘System.out.println’ statements as a shortest path, which is a bad practice in the production level applications. Logging serves as a crucial tool for developers by providing insights into the inner workings of an application. It also assists in diagnosing issues, and helping in the overall monitoring and maintenance of the software. In this article, we will learn logger in Spring Boot and related concepts with extensive amount of examples. Table of Contents Toggle What is a Log?What is Logging In Spring Boot?What are the components in Logging in Spring Boot?Logging LevelsLogging ConfigurationConfiguration Properties Logging OutputWhat is Logger In Spring Boot?Logger InterfaceLogger InitializationLogger FactoryGenerating Log MessagesLogging LevelsLog FormattingExample usage of a logger in Spring Boot applicationWhat are the benefits of Logging in Spring Boot?Logger in Spring Boot With LombokStep-by-step Guide to implement logging in a Spring Boot applicationStep#1: Create a New Spring Boot ProjectStep#2: Add Spring Boot Starter DependenciesStep#3: Configure Logging Step#3A: Configure Logging with application.propertiesStep#3B: Configure Logging with logback.xmlStep#4: Create a Service Class with LoggingStep#5: Run the ApplicationStep#6: Observe Log OutputStep#7: Configure Different Logging LevelsStep#8: Log to a FileStep#9: Run the Application and Observe Log OutputStep#10: Additional Customizationlogback.xml vs. application.propertiesExample of logback.xmlExample of application.propertiesFAQHow are logging enabled in Spring Boot? What is a Log? In software development, “log” represents a report containing the history of events, activities, or messages generated by a computer program throughout its execution. These logs are used to collect relevant information about the program’s behavior, errors, warnings, and other noticeable events that take place while the program is running. Moreover, logs are very important for diagnosing issues, monitoring system performance, and troubleshooting in an application. Logs can be very useful to developers in debugging, monitoring, auditing, and analyzing the applications. What is Logging In Spring Boot? Logging refers to the practice of gathering and managing log messages generated by a software application during its runtime. Spring Boot offers a flexible logging framework that allows developers to configure and control how log messages are generated, formatted, and stored. This logging framework is built on top of the popular SLF4J (Simple Logging Facade for Java) and Logback libraries. In simple words, Logging is a basic practice in software development process that offers developers an understanding of what is happening within a program. What are the components in Logging in Spring Boot? Let’s go through the various components under Logging in Spring Boot. Logging Levels Spring Boot contains different logging levels to classify the log messages. The common log levels are DEBUG, INFO, WARN, ERROR, and TRACE. We can choose the suitable log level for a specific message based on our requirement & its importance. Logging Configuration Spring Boot applications can be configured to use different logging implementations. By default, Spring Boot uses Logback as the default logging framework, but it is also capable of supporting other common logging frameworks like Log4j2 and JUL (Java Util Logging) etc. We can configure the required logging implementation by adding the corresponding dependency to our project’s build configuration. Configuration Properties Configuration properties of Spring Boot allow us to customize various characteristics of logging, such as log level thresholds for different loggers, log output formats, and log file locations. These properties can be specified in the ‘application.properties’ or ‘application.yml’ files. Logging Output Log messages can be in the form of various outputs, such as the console, log files, database entries, or even external logging services. Spring Boot provides configuration options to control where log messages are sent. It also includes the ability to specify rolling log files to manage log rotation and retention based on the specified size of the file. ♥ Along with application-specific log messages, Spring Boot’s logging framework can also capture various system events and information, such as server startup details, database connection information, and HTTP request/response logs. What is Logger In Spring Boot? A logger is an object that allows us to generate log messages within the application. Loggers are part of the logging framework provided by Spring Boot and are used to record various events, activities, and information during the runtime of our application. These log messages provide information into the behavior of our application, assist in troubleshooting, and help in monitoring and maintaining the application’s health. Below are some key points about logger in Spring Boot: Logger Interface Spring Boot internally uses the Logger interface from the SLF4J (Simple Logging Facade for Java) library as the primary abstraction for creating log messages. We need to connect with the logger interface to generate log messages in our code. Logger Initialization Logger instances are generally initialized at the class level as private static final field. This practice ensures that the logger is shared across instances of the same class and eliminates the overhead of logger creation. Logger Factory Spring Boot’s logging framework uses a logger factory to create logger instances behind the scenes. The factory is responsible for determining which logging implementation (e.g., Logback, Log4j2) to use and instantiates the appropriate logger accordingly. Generating Log Messages In order to generate log messages, we call methods on the logger instance with respect to the desired logging level. For example, to generate an informational log message, you would use logger.info(“Message text”). Logging Levels Logging levels are used to categorize log messages based on their severity and importance. Each logging level corresponds to a specific severity level, which helps developers understand the nature of the logged events. Spring Boot, along with logging frameworks like SLF4J and Logback, provides a set of standard logging levels that are commonly used to indicate different levels of severity. These are trace, debug, info, warn, and error. Below is the arrangement of the levels based on their severity: trace < debug < info < warn < error By default info & above level messages are enabled. In order to receive other level messages, go to application.properties and add below entries accordingly: logger.level.root=TRACE Since the TRACE has the lowest sevirity, in this case all levels messages will appear. Log Formatting Log messages can include placeholders for variables and parameters. The logger framework automatically formats the log messages with the provided values, enhancing readability and making it easier to understand the context of the log entry. However, we can customize the format of the log messages as per our requirement. Example usage of a logger in Spring Boot application import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); public void performAction() { logger.info("Performing an action..."); // ... code for performing an action ... logger.debug("Action completed successfully."); } } In this example, the LoggerFactory is used to create an instance of the logger for the MyService class. The logger is then used to generate log messages with different logging levels. What are the benefits of Logging in Spring Boot? Logging plays a key role in Spring Boot applications, offering a variety of considerable benefits that improve development, troubleshooting, and maintenance processes. Below are some key reasons why logging is beneficial in Spring Boot: Debugging and Troubleshooting: Logs act as a useful source of information for analyzing problems when issues arise in an application. We can identify the root causes of issues and implement the actual solutions by analyzing the sequence of log messages and understanding the context in which errors/exceptions occurred. Real-time Insight: Logs provide real-time insights into how an application behaves during its runtime. This helps us understand how different components of the application work together and identify any unexpected behaviors. Monitoring and Performance Optimization: Even we can monitor the performance of their applications through logs. We can identify bottlenecks and optimize the application’s performance by tracking metrics such as response times, database queries, and resource consumption. Auditing and Compliance: In many applications, particularly those dealing with vulnerable data or financial transactions, logging is essential for auditing and compliance purposes. Logs can record user actions, system events, and security-related incidents, providing a recognizable history of activities for regulatory compliance and security audits. Release and Deployment: Logs play a crucial role in ensuring a smooth transition during the release and deployment process. We can quickly identify any issues that might have occurred during the deployment process and roll back if necessary by analyzing logs generated during deployment. Continuous Improvement: We can identify patterns of errors, user behavior, and system behavior by regularly reviewing logs. This information can guide the development team in making informed decisions to improve the application’s overall quality and user experience. Communication and Collaboration: In collaborative development environments, logs provide a common ground for communication between team members. Developers can share log data to discuss issues, brainstorm solutions, and coordinate efforts to address problems. Historical Record: Logs serve as a historical record of an application’s activities and events. This historical perspective can be valuable for tracking changes, understanding the evolution of the application, and learning from past experiences. Proactive Issue Detection: Effective logging enables developers to detect issues before they escalate into critical problems. By setting up alerts and monitoring tools that analyze log data in real-time, development teams can identify defects and probable problems, allowing them to take proactive actions. Documentation: Logs act as a form of documentation for an application’s runtime behavior. They can provide insights into how different parts of the application interact, what data flows through the system, and how external integrations are functioning. In summary, logging in Spring Boot is not merely a technical requirement; it’s a fundamental practice that empowers developers to build, maintain, and enhance applications effectively. By providing valuable insights, aiding troubleshooting, and supporting performance optimization, logging contributes to the overall reliability, stability, and success of Spring Boot applications. Logger in Spring Boot With Lombok If we use Lombok in our project, we can apply Lombok’s @Slf4j annotation to make the task even easier. Lombok’s @Slf4j annotation in a Spring Boot application simplifies the process of implementing logging by automatically generating a logger instance, which we can use to create log messages at various logging levels. This annotation automatically generates a logger field for your class. It offers us to easily create log messages without manually initializing the logger. This approach eliminates the need to manually declare and initialize logger instances in our classes. Below are the steps how we can do it: Step#1: Add Lombok Dependency: First of all, make sure you have the Lombok dependency added to your Spring Boot project’s build configuration (e.g., build.gradle or pom.xml). Step#2: Annotate Your Class: Annotate your class with the @Slf4j annotation. This annotation instructs Lombok to generate a logger field for your class. Step#3: Use the Logger: You can use the generated logger to create log messages at required logging levels. For example, let’s implement logging in a Spring Boot application using Lombok: import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Slf4j @Service public class MyService { public void performAction() { log.info("Performing an action..."); try { // ... code for performing the action ... log.debug("Action completed successfully."); } catch (Exception e) { log.error("Error while performing the action", e); } } } As shown in this example, the @Slf4j annotation is used on the MyService class. Lombok will automatically generate a logger field named log for this class. Inside the performAction method, we can use the log logger to create log messages. The info, debug, and error methods are used to log messages at different logging levels. Lombok takes care of initializing the logger instance and producing the necessary code to integrate with the logging framework (SLF4J). Step-by-step Guide to implement logging in a Spring Boot application Let’s understand the step-by-step process to implement logging in Spring Boot. Step#1: Create a New Spring Boot Project Create a new Spring Boot project using your preferred method (such as Spring Initializr or an IDE like STS, IntelliJ or Eclipse). If you already have a project and want to implement logging in it, ignore this step. Step#2: Add Spring Boot Starter Dependencies Open your project’s build configuration file (build.gradle for Gradle or pom.xml for Maven) and include the necessary Spring Boot starter dependencies. Please note that if you have even a basic Spring Boot project, you don’t need to add any additional dependency for logging. It will automatically be added by Spring Boot. For example, below is a basic Spring boot starter project dependency. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> Step#3: Configure Logging There are two approaches to configure logging in Spring Boot. Providing logging configurations in application.properties is the default way of implementation. Another approach is to include logback.xml or logback-spring.xml in your class path to take benefits of all types of logging-related configurations. Let’s configure it by using both approaches one by one. Step#3A: Configure Logging with application.properties As aforementioned, Spring Boot’s logging framework uses the application.properties or application.yml file to configure logging settings by default. Open the src/main/resources/application.properties file and add logging-related configuration: #Set root logging level logging.level.root=INFO #Set logging level for specific packages/classes logging.level.org.springframework=INFO logging.level.com.example=DEBUG #Set log messages of a particular pattern on a console logging.pattern.console=%c-[%level]- %d-%m-%n #To get Log messages in a file logging.file.name=Applog.log logging.file.name=D:/Applog.txt logging.pattern.file=%c-[%level]- %d-%m-%n In this example, we have set the root logging level to INFO and configured different logging levels for package (org.springframework) and a custom package (com.example). In order to get log messages in a particular format, we have set the logging pattern for console and file output both. We can adjust these levels based on our preferences and requirements. The meaning of symbols in log pattern are as below: %m - Log Message %level- Logger Level %d - date & time %c - Category/Class name %n - platform independent new line Step#3B: Configure Logging with logback.xml Create a logback.xml file in the src/main/resources directory. This file will contain the configuration for the logging framework. In order to get the all the benefits of logging at one place, include logback.xml or logback-spring.xml in your classpath(src/main/resources). For a deep understanding of logback.xml, kindly visit a separate article on logback.xml configuration examples. Here’s a simple example of a logback.xml configuration: <configuration> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="CONSOLE" /> </root> </configuration> In this example, the configuration sets up a console appender named CONSOLE, which sends log messages to the console. The <encoder> section specifies the pattern for formatting log messages. The pattern includes the timestamp, thread name, log level, logger name, message, and a line break. The root logger is configured to use the CONSOLE appender and has a logging level set to INFO. Step#4: Create a Service Class with Logging Create a service class where you’ll implement logging using the configured logback.xml. import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class MyService { private final Logger logger = LoggerFactory.getLogger(MyService.class); public void performAction() { logger.info("Performing an action..."); try { // ... code for performing the action ... logger.debug("Action completed successfully."); } catch (Exception e) { logger.error("Error while performing the action", e); } } } Step#5: Run the Application Run your Spring Boot application. The log messages will appear in the console, formatted according to the pattern specified in the logback.xml configuration. Step#6: Observe Log Output As you interact with your application or trigger the methods that include logging, observe the log output in the console. The log messages should follow the formatting defined in the logback.xml configuration. Step#7: Configure Different Logging Levels We can configure different logging levels for specific packages or classes using the logback.xml configuration. For example, if we want to set a different logging level for a specific package, we can add a logger configuration within the <configuration> element as shown below: <configuration> <!-- ... existing configuration ... --> <!-- Configure a specific package to use DEBUG level --> <logger name="com.example.test" level="DEBUG" /> <!-- ... more configurations ... --> </configuration> In this example, the com.example.test package will log messages at the DEBUG level. Step#8: Log to a File To log messages to a file, we can add a FileAppender to our logback.xml configuration as below: <configuration> <!-- ... existing configuration ... --> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>myapp.log</file> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </configuration> In this example, a FileAppender named FILE is added to log messages to a file named myapp.log. Step#9: Run the Application and Observe Log Output Run your Spring Boot application again after adding the configurations for different logging levels and logging to a file. Interact with your application or trigger the methods that include logging. Observe the log output in both the console and the log file (myapp.log in this case). By completing these steps, we have implemented logging in a Spring Boot application. We have customized logging levels, defined output formats, and even directed log messages to a file. Step#10: Additional Customization Logback offers various customization options for advanced scenarios. We can configure additional appenders (like rolling files), customize log format patterns, and even integrate external logging services. For more advanced configurations and options, you can refer to the official Logback documentation: Logback Documentation. logback.xml vs. application.properties Let’s take an example of configuring a file appender in logback.xml and then convert that configuration into application.properties. Example of logback.xml <configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>myapp.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>myapp.%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="FILE" /> </root> </configuration> In this logback.xml configuration, we have a file appender named FILE that logs messages to a rolling log file named myapp.log. The log output format includes a timestamp, thread name, log level, logger name, message, and line break. Example of application.properties To convert the above logback.xml configuration into application.properties, open the src/main/resources/application.properties file and configure the file appender as follows: # Set root logging level logging.level.root=INFO # Set log output format logging.pattern.file=%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n # Configure file appender logging.appender.file.type=ch.qos.logback.core.rolling.RollingFileAppender logging.appender.file.name=myapp.log logging.appender.file.append=true logging.appender.file.rollingPolicy.type=ch.qos.logback.core.rolling.TimeBasedRollingPolicy logging.appender.file.rollingPolicy.fileNamePattern=myapp.%d{yyyy-MM-dd}.log In this example configuration, The root logging level is set to INFO. The logging.appender.file section configures the file appender (FILE) with the specified file name, append mode, layout, and rolling policy, just like in the logback.xml example. In this way, by converting the file appender configuration from logback.xml into application.properties, we can achieve the same logging behavior using the Spring Boot property-based configuration approach. For other detailed tutorials on Spring Boot, kindly visit Spring Boot Tutorials. FAQ How are logging enabled in Spring Boot? In order to enable and configure logging in Spring Boot, follow these steps: 1) Include any starter project dependency: For example, below dependency is sufficient to obtain benefits of logging API. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> 2) Configure Logging: Spring Boot provides a default logging configuration that works for most of the applications. However, we can customize the logging configuration by creating a logback.xml (for Logback) file in our project’s classpath. This file allows us to specify log levels, log file locations, and more. Below is an example of logback.xml. <configuration> <appender name="file" class="ch.qos.logback.core.FileAppender"> <file>myapp.log</file> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="info"> <appender-ref ref="file"/> </root> </configuration> 3) Configure Logger in the Application: We can use logging in our Spring Boot application by creating a Logger object into our classes and then using it to log messages. For example, below is the sample code to configure logger in the service layer of a Spring Boot application: import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Service public class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); public void doSomething() { logger.info("This is an informational log message."); logger.error("This is an error log message."); } } 4) Testing Log Messages: By default, Spring Boot logs are displayed in the console. Depending on our configuration, logs may also be written to log files. In our case, we have already included logback.xml and configure file appender, so our log messages should appear in the specified file also. We can adjust log levels and view logs in real-time while our application is running. Related