当前位置: 代码迷 >> 综合 >> springboot org.slf4j.Logger 添加日志到文件 logback-spring.xml
  详细解决方案

springboot org.slf4j.Logger 添加日志到文件 logback-spring.xml

热度:133   发布时间:2023-10-10 05:03:08.0
  1. springboot项目中在resources资源目录下添加logback-spring.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="60 seconds" debug="false"><contextName>logback</contextName><!--输出到控制台--><appender name="console" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern></encoder></appender><!--按天生成日志--><appender name="logFile"  class="ch.qos.logback.core.rolling.RollingFileAppender"><Prudent>true</Prudent><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><FileNamePattern>applog/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log</FileNamePattern></rollingPolicy><layout class="ch.qos.logback.classic.PatternLayout"><Pattern>%d{yyyy-MM-dd HH:mm:ss} -%msg%n</Pattern></layout></appender><logger name="com.jianxin" additivity="false"><appender-ref ref="console"/><appender-ref ref="logFile" /></logger><root level="info"><appender-ref ref="console"/><appender-ref ref="logFile" /></root></configuration>
  1. 记录日志处使用即可:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
logger.info("【"+service.getServiceId()+"】:"+service.getHost()+":"+service.getPort());
  1. 其中,logback-spring.xml配置文件中:
<root level="info"><appender-ref ref="console"/><appender-ref ref="logFile" />
</root>

level可以调整日志记录级别,如:debug,info,error等;console和logFile分别对应着上边<appender>中的name。

  相关解决方案