问题
想使用Spring Boot中日志输出,这样以后遇到问题,就可以翻看日志数据,看看程序运行的过程,便于排查错误。
logback基础配置
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</configuration>
application.properties
logging.path=logs
上面两步,主要就是对spring-boot对最基础日志配置。
按日期分割
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}" />
<include
resource="org/springframework/boot/logging/logback/console-appender.xml" />
<appender name="DAY_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd_HH-mm}.log</fileNamePattern>
<maxHistory>365</maxHistory>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DAY_FILE" />
</root>
</configuration>
**Note:**这里的DAY_FILE,其实主要就是参考org/springframework/boot/logging/logback/file-appender.xml
进行配置。
Java代码调用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DemoController {
private final static Logger logger = LoggerFactory.getLogger(DemoController.class);
public Demo greeting(@RequestParam(value="serviceId", defaultValue="World") String serviceId) {
logger.info("serviceId-->" + serviceId);
...
}
}
总结
没有必要去弄颜色输出,因为我的命令行工具已经弄好了主题,我使用的是德古拉主题;使用Logback理由,是因为Spring推荐使用。
参考: 77. Logging Spring boot——logback 基础使用篇(一) 设置spring-boot的logging Spring Boot 日志记录 SLF4J USING LOGBACK WITH SPRING BOOT
来源:oschina
链接:https://my.oschina.net/u/168875/blog/1828904