目录
在Spring Boot项目中使用日志框架是一种常见且很有必要的实践。Spring Boot默认集成了Logback日志框架,但也支持其他日志框架,如Log4j2。以下分别对使用Logback和Log4j2的配置和使用进行介绍。
1. Logback
Logback是默认的日志框架,因此在Spring Boot项目中使用Logback不需要特别配置。
1.1. pom依赖导入
默认情况下,`spring-boot-starter`中已经包括了对Logback的支持。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
1.2. 配置文件及日志格式自定义
在`src/main/resources`下创建`application.properties`或`application.yml`来配置Logback。并对日志格式进行自定义。
****application.yml****
logging:
level:
root: INFO
com.myapp: DEBUG
file:
name: myapp.log
pattern:
console: "%clr(%d{yyyy-MM-dd HH:mm:ss}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(%pid){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{40} - %msg%n"
****application.properties****
logging.level.root=INFO
logging.level.com.myapp=DEBUG
logging.file.name=myapp.log
logging.pattern.console=%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd} [%thread] %-5level %logger{36} - %msg%n
1.3. 如何创建日志对象
在类中创建日志对象的标准方式是使用SLF4J的Logger和LoggerFactory。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyService {
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
public void someMethod() {
logger.info("Info message");
logger.debug("Debug message");
}
}
1.4. 实际应用
在服务类中实际使用日志。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
public void process() {
logger.info("Started processing...");
// ... 业务逻辑
logger.info("Processing finished.");
}
}
1.5. 测试
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void testProcess() {
myService.process();
// 日志输出在控制台或日志文件中,不需要在单元测试中验证
}
}
2. Log4j2
Log4j2被认为在性能上优于Logback特别是在多线程场景下。它支持异步日志记录。
2.1. pom依赖导入
要用Log4j2替换Logback,需要排除Logback依赖并引入Log4j2。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
2.2. 配置文件及目录
在`src/main/resources`下创建`log4j2.xml`或`log4j2-spring.xml`配置文件。
****log4j2-spring.xml****
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="LogFile" fileName="logs/myapp.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="LogFile"/>
</Root>
</Loggers>
</Configuration>
2.3. 如何创建日志对象
与Logback类似,但使用Log4j2的Logger和LogManager。
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyService {
private static final Logger logger = LogManager.getLogger(MyService.class);
public void someMethod() {
logger.info("Info message");
logger.debug("Debug message");
}
}
2.4. 实际应用
与前面的Logback示例类似,在服务类中实际使用日志。
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private static final Logger logger = LogManager.getLogger(MyService.class);
public void process() {
logger.info("Started processing...");
// ... 业务逻辑
logger.info("Processing finished.");
}
}
2.5. 测试
与Logback的测试相同。
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void testProcess() {
myService.process();
// 日志输出在控制台或日志文件中,不需要在单元测试中验证
}
}
3. 总结
对于Spring Boot的日志管理,Logback和Log4j2都是优秀的选择,它们都支持通过配置文件自定义日志级别、格式和输出目的地。Logback是Spring Boot的默认配置,而Log4j2提供了额外的性能优势,特别是在多线程和高并发场景下。
创建日志对象和在代码中使用日志的方式基本相同,不同之处在于Logger的来源:Logback使用SLF4J的`LoggerFactory`获取Logger,而Log4j2使用自己的`LogManager`。
最佳实践建议开发者根据应用的需求和偏好选择合适的日志框架,并确保在生产环境中灵活配置日志级别以避免不必要的性能开销。同时,对于日志数据的管理,尤其是在分布式环境中,集成中央日志系统(例如ELK栈)是常见且有用的做法。
最后,漫漫IT成长之路让我们一起升级打怪!!!