This example shows how to use Logback as an implementation provider for SLF4j in a Spring application.
Example
Maven dependencies
pom.xml<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.2.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.3.16</version>
</dependency>
Because logback-classic natively implements the SLF4J API, there is no need to include the SLF4J dependency separately.
With Spring 5, the new spring-jcl module can automatically switch from JCL to SLF4J when it finds SLF4J dependencies in the classpath. This eliminated the need for JCL exclusions that were necessary in older versions. For versions of Spring older than 5, refer to the example here.
A Bean using SLF4J API
package com.logicbig.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyBean {
private static Logger log = LoggerFactory.getLogger(MyBean.class);
public void doSomething() {
log.info("doing something");
}
}
Logback configuration file
src\main\resources\logback.xml<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yy-MM-dd HH:mm:ss:SSS} %5p %t %c{2}:%L - %m%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="stdout"/>
</root>
</configuration>
Main class
package com.logicbig.example;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ExampleMain {
@Bean
public MyBean myBean() {
return new MyBean();
}
public static void main(String[] args) {
ConfigurableApplicationContext context =
new AnnotationConfigApplicationContext(ExampleMain.class);
MyBean bean = context.getBean(MyBean.class);
bean.doSomething();
}
}
Output25-11-11 22:14:10:675 INFO com.logicbig.example.ExampleMain.main() c.l.e.MyBean:10 - doing something
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 5.0.0.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- logback-classic 1.3.16 (logback-classic module)
- JDK 25
- Maven 3.9.11
|