JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

How to configure logback (SLF4J) logging to spring boot applications?


Logback makes an excellent logging framework for enterprise applications – it’s fast, have simple but powerful configuration options, and comes with a small memory footprint.

We will discuss about Logback in this page. The Spring Boot is using Logback as a default logger. By default, the SLF4j Logging is included in the Spring Boot starter package. So no additional dependencies are required.

Maven Dependency Tree Trace
$ mvn dependency:tree

[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-tutorials 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.2.RELEASE:compile
[INFO] |  |  +- ch.qos.logback:logback-classic:jar:1.1.11:compile
[INFO] |  |  |  +- ch.qos.logback:logback-core:jar:1.1.11:compile
[INFO] |  |  |  \- org.slf4j:slf4j-api:jar:1.7.24:compile
[INFO] |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.24:compile
[INFO] |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.24:compile
[INFO] |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.24:compile

In spring boot, you can handle all your logging related configurations with in "application.properties" file itself:

application.properties
logging.level.org.springframework.web=ERROR
logging.level.com.java2novice=DEBUG
logging.pattern.console=%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n
logging.path=logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
                    

Spring boot also allows you to create standard logback.xml file in the resources directory. This will override the Spring Boot logging template.

All you need to do is, specify your logback configuration file in application.properties as shown below:

application.properties
logging.config=logback.xml

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

	<appender name="FILE-AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>/logs/debug.log</file>
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<Pattern>%d{yyyy-MM-dd HH:mm:ss} - %msg%n</Pattern>
		</encoder>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!-- rollover daily -->
			<fileNamePattern>/logs/archived/debug.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<maxFileSize>10MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
    </appender>

	<logger name="com.java2novice" level="debug" additivity="false">
		<appender-ref ref="FILE-AUDIT" />
	</logger>

	<root level="error">
		<appender-ref ref="FILE-AUDIT" />
	</root>

</configuration>

Spring boot also provides profile based loggings. As we discussed in the previous pages, we can maintain multiple properties for each profile, so that spring boot will pick the right profile on demand.

We can also handle our standard way of xml configurations with logback.xml file. Spring boot supports these configurations. Create a logback-spring.xml in the root of the classpath, to take advantage of the templating features provided by Spring Boot with multiple profiles in it, as shown below:

logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />

    <springProfile name="dev,staging">
        <logger name="guru.springframework.controllers" level="DEBUG" additivity="false">
            <appender-ref ref="CONSOLE" />
        </logger>
    </springProfile>

    <springProfile name="production">
        <logger name="guru.springframework.controllers" level="WARN" additivity="false">
            <appender-ref ref="FILE" />
        </logger>
    </springProfile>

    <if condition='property("spring.profiles.active").contains("dev")'>
        <then>
            <logger name="guru.springframework.helpers" level="DEBUG" additivity="false">
                <appender-ref ref="CONSOLE" />
            </logger>
        </then>
        <else>
            <logger name="guru.springframework.helpers" level="WARN" additivity="false">
                <appender-ref ref="FILE" />
            </logger>
        </else>
    </if>
</configuration>
<< Previous Program | Next Program >>

Spring-Boot Examples

  1. Spring-Boot initial setup.
  2. Spring-Boot hello world example
  3. What is spring-boot-starter-parent in Spring-Boot pom.xml file?
  4. What is @SpringBootApplication annotation in spring boot?
  5. What is application.properties in spring boot?
  6. What is @ConfigurationProperties annotation in spring boot?
  7. Spring Boot @ConfigurationProperties example
  8. Spring Boot @ConfigurationProperties Property Validation
  9. Difference between @ConfigurationProperties and @Value
  10. Spring boot web application configurations.
  11. How to run spring boot application through command line?
  12. How to run spring boot as a standalone application (non-web)?
  13. Spring boot property resolution order.
  14. Spring Boot – Profile based properties example.
  15. How to configure logback (SLF4J) logging to spring boot applications?
  16. How to update application context path in spring boot?
  17. How to disable spring logo banner in spring boot?
  18. Spring Data JPA with Spring Boot Applications - Oracle - example
  19. Spring Data JPA with Spring Boot Applications - MySql example
  20. How to configure Spring Boot to show Hibernate SQL Query in logs?
  21. Spring Boot – List all Beans loaded in the ApplicationContext
  22. How to load external property files into Spring Boot application?
  23. How to rename application.properties file in Spring Boot application?
  24. How to configure multiple DataSources (Databases) with Spring Boot and Spring Data?
Knowledge Centre
What is race condition?
A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.