Zba*_*ian 7 java logging spring-boot
我是 Spring Boot 的新手,我刚刚设置了 logback 以将日志写入自定义日志文件。一切正常,我已成功将自定义日志消息写入文件,但是当引发异常时,错误并且堆栈跟踪未写入文件。
src/main/resources/ logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</encoder>
</appender>
<timestamp key="timestamp" datePattern="yyyy-MM-dd"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/app-${timestamp}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- retain 30 days logs -->
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
Run Code Online (Sandbox Code Playgroud)
src/main/resources/ application.properties
logging.config=classpath:logback.xml
Run Code Online (Sandbox Code Playgroud)
主要类:
@SpringBootApplication
public class DemoApplication {
private static final Logger logger = Logger.getLogger("DEMO");
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
logger.log(Level.INFO, "main called");
throw new IllegalArgumentException("This is a test");
}
}
Run Code Online (Sandbox Code Playgroud)
以及不在日志文件中的堆栈跟踪:
Exception in thread "main" java.lang.IllegalArgumentException: This is a test
00:06:54.179 [main] ERROR DEMO - This is an error
at com.demo.DemoApplication.main(DemoApplication.java:18)
Run Code Online (Sandbox Code Playgroud)
PS:我尝试更改根级别日志记录:<root level="ERROR">但问题仍然存在,我在日志文件中看不到异常。
1.你必须使用slf4j + logback,看起来你正在使用java utillogging 2.尝试捕获异常并记录错误,否则logback无法捕获异常
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
private static final Logger logger = LoggerFactory.getLogger("DEMO");
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
logger.info("main called");
try {
throw new IllegalArgumentException("This is a test");
} catch(Exception e) {
logger.error("", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2890 次 |
| 最近记录: |