Spring Boot 入门 - 日志管理

Posted 记忆的痕迹

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 入门 - 日志管理相关的知识,希望对你有一定的参考价值。

Spring Boot支持JUL,Log4J2和Logback。
 1.默认设置 
  -采用SLF4J + Logback 
 - 日志只输出到控制台 
 -级别Level为INFO 
 -日志文件rotate大小为10Mb 
 -输出格式为:时间戳 级别 进程ID --- [线程名] 类名 日志内容 

 引用: 2018-01-22 18:54:16.076  INFO 8296 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)

2.输入到文件

   引用: logging.path=d:

   会在该目录下创建spring.log文件,输出内容和控制台相同。 

3.详细配置 

   src/main/resources/application.properties 

 1 # Location of the log file. 
 2 logging.file=d:\\spring-boot-demo.log
 3 # Appender pattern
 4 logging.pattern.console=%date %-5level %logger{0} - %msg%n
 5 logging.pattern.file=%date %-5level [%thread] %logger{0} [%file:%line] - %msg%n
 6 logging.pattern.level=%5p
 7 # Log levels - root
 8 logging.level.=DEBUG
 9 # Log levels - package
10 logging.level.org.springframework.web=INFO
11 # Log levels - class
12 logging.level.com.rensanning.springboot.HomeController=TRACE

注意:logging.file 和 logging.path不能同时设置 

4.测试代码 
src/main/java/com/rensanning/springboot/HelloController.java 

 1 import org.slf4j.Logger;
 2 import org.slf4j.LoggerFactory;
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 @RestController
 7 public class HelloController {
 8     
 9     private final Logger log = LoggerFactory.getLogger(this.getClass());
10     
11     @RequestMapping("/")
12     public String index() {
13         
14         // Log a simple message
15         log.debug("debug level log");
16         log.info("info level log");
17         log.warn("warn level log");
18         log.error("error level log");
19         
20         return "Hello world from Spring Boot!";
21     }
22     
23 }

 启动应用后访问 http://localhost:8080/。 

5.外部配置 
  src/main/resources/ 

  • Logback -> logback.xml 或 logback-spring.xml
  • Log4j2 -> log4j2.xml 或 log4j2-spring.xml
  • JUL -> logging.properties

 src/main/resources/logback-spring.xml 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <configuration scan="true" scanPeriod="30 seconds">
 3 
 4     <property name="log.base" value="d:" />
 5     <property name="log.level" value="DEBUG" />
 6 
 7     <!-- Appenders -->
 8     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
 9         <encoder>
10             <pattern>%-5level %logger{0} - %msg%n</pattern>
11         </encoder>
12     </appender>
13 
14     <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
15         <file>${log.base}/SpringSample.log</file>
16         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
17             <fileNamePattern>${log.base}/SpringSample.%d{yyyyMMdd}.%i.log</fileNamePattern>
18             <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
19                 <maxFileSize>5MB</maxFileSize>
20             </timeBasedFileNamingAndTriggeringPolicy>
21         </rollingPolicy>
22         <encoder>
23             <pattern>%date %-5level [%thread] %logger{0} [%file:%line] - %msg%n</pattern>
24         </encoder>
25     </appender>
26     
27     <!-- 3rdparty Logger -->
28     <logger name="org.springframework" level="${log.level}" />
29     <logger name="org.apache.commons" level="INFO" />
30     <logger name="org.apache.tiles" level="INFO" />
31     <logger name="org.apache.ibatis" level="${log.level}" />
32     <logger name="org.apache.shiro" level="${log.level}" />
33     <logger name="org.dozer" level="INFO" />
34     <logger name="org.scribe" level="${log.level}" />
35     
36     <!-- Application Logger -->
37     <logger name="com.rensanning.springboot" level="${log.level}" />
38     
39     <!-- Root Logger -->
40     <root level="${log.level}">
41         <appender-ref ref="STDOUT" />
42         <appender-ref ref="FILE" />
43     </root>
44 
45 </configuration>

 启动应用后访问 http://localhost:8080/。 

 控制台输出内容: DEBUG HelloController - debug level log 
        INFO  HelloController - info level log 
        WARN  HelloController - warn level log 
        ERROR HelloController - error level log

 SpringBoot默认配置文件 :
 base.xml(console-appender.xml file-appender.xml) 
 https://github.com/spring-projects/spring-boot/blob/master/spring-boot/src/main/resources/org/springframework/boot/logging/logback/base.xml 

 1 <included>
 2     <include resource="org/springframework/boot/logging/logback/defaults.xml" />
 3     <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
 4     <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
 5     <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
 6     <root level="INFO">
 7         <appender-ref ref="CONSOLE" />
 8         <appender-ref ref="FILE" />
 9     </root>
10 </included>

6.部分设置(引入base.xml) 
 src/main/resources/application.properties 

 引用:logging.path=d:

 src/main/resources/logback-spring.xml 

1 <?xml version="1.0" encoding="UTF-8"?>
2 <configuration>
3     <include resource="org/springframework/boot/logging/logback/base.xml"/>
4     <logger name="com.rensanning.springboot" level="WARN" additivity="false">
5         <appender-ref ref="CONSOLE"/>
6         <appender-ref ref="FILE"/>
7     </logger>
8 </configuration>

启动应用后访问 http://localhost:8080/。 

使用<springProfile> 
src/main/resources/application.properties 

引用:logging.path=d:
src/main/resources/logback-spring.xml 
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <configuration>
 3     <include resource="org/springframework/boot/logging/logback/base.xml" />
 4     <springProfile name="dev,staging">
 5         <logger name="com.rensanning.springboot" level="DEBUG" additivity="false">
 6             <appender-ref ref="CONSOLE" />
 7         </logger>
 8     </springProfile>
 9     <springProfile name="production">
10         <logger name="com.rensanning.springboot" level="WARN" additivity="false">
11             <appender-ref ref="FILE" />
12         </logger>
13     </springProfile>
14 </configuration>

添加VM参数 -Dspring.profiles.active=dev 启动应用后访问 http://localhost:8080/。 

使用<if><then><else> 

Logback通过Janino包还支持在配置文件中条件判断。 http://janino-compiler.github.io/janino/ 

<dependency>
   <groupId>org.codehaus.janino</groupId>
   <artifactId>janino</artifactId>
   <version>2.7.8</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <if condition=‘property("spring.profiles.active").contains("dev")‘>
        <then>
            <logger name="com.rensanning.springboot" level="DEBUG" additivity="false">
                <appender-ref ref="CONSOLE" />
            </logger>
        </then>
        <else>
            <logger name="com.rensanning.springboot" level="WARN" additivity="false">
                <appender-ref ref="FILE" />
            </logger>
        </else>
    </if>
</configuration>

7.使用Log4J2

 pom.xml 

 1 <dependency>  
 2     <groupId>org.springframework.boot</groupId>  
 3     <artifactId>spring-boot-starter-web</artifactId>  
 4     <exclusions>  
 5         <exclusion>  
 6             <groupId>org.springframework.boot</groupId>  
 7             <artifactId>spring-boot-starter-logging</artifactId>  
 8         </exclusion> 
 9     </exclusions> 
10 </dependency>  
11 <dependency> 
12     <groupId>org.springframework.boot</groupId>  
13     <artifactId>spring-boot-starter-log4j2</artifactId>  
14 </dependency>

 src/main/resources/log4j2-spring.xml 

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="60">
    <Properties>
        <Property name="log-path">d:</Property>
    </Properties>
    <Appenders>
        <Console name="Console-Appender" target="SYSTEM_OUT">
            <PatternLayout>
                <pattern>
                    [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>>
            </PatternLayout>
        </Console>
        <File name="File-Appender" fileName="${log-path}/springboot_log.log" >
            <PatternLayout>
                <pattern>
                    [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.rensanning.springboot" level="info" additivity="false">
            <AppenderRef ref="Console-Appender"/>
        </Logger>
        <Root>
            <AppenderRef ref="File-Appender"/>
            <AppenderRef ref="Console-Appender"/>
        </Root>
    </Loggers>
</Configuration>

启动应用后访问 http://localhost:8080/。 

          --END--

 

 

 

 
















以上是关于Spring Boot 入门 - 日志管理的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 日志管理

spring boot快速入门 10: 日志使用

Spring Boot 入门:集成 WebSocket, 实时显示系统日志

Spring Boot 入门:集成 treetable 和 zTree 实现树形图

Spring boot 入门:集成 Shiro 实现登陆认证和权限管理

Spring Boot 入门 404 错误