在Spring Boot中配置日志(根据环境的区别)

刺激

    • spring-bootアプリケーションのlogを残したいな。

 

    • 環境ごとに出力を変えたい

本番ならば特定のディレクトリにファイルでlogLevelはinfoかな
ローカルならば標準出力にlogLevelはdebugかな

仓库

我会使用之前创建的这个项目:https://github.com/mijinco0612-self-improvement/spring-auth0

试一试

首先,在pom中添加dependency。

        <!-- Logging -->
        <dependency>
            <groupId>org.codehaus.janino</groupId>
            <artifactId>janino</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-access</artifactId>
        </dependency>

只需输出的话,只用logback就可以了。
如果需要根据不同环境进行配置,那就需要使用janino。

将logback.xml添加到resources目录中。

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!-- 共通設定 -->
    <property name="LOG_DIR" value="/var/www/logs" />
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/spring-auth0.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_DIR}/spring-auth0.log.%d{yyyy-MM-dd}</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} |%t| [%p] %c %msg %n</pattern>
        </encoder>
    </appender>
    <if condition='isDefined("spring.profiles.active")'>
        <then>
            <include resource="logback/${spring.profiles.active}.xml"/>
        </then>
        <else>
            <include resource="logback/prd.xml"/>
        </else>
    </if>
</configuration>

在资源文件夹(resources>logback)中创建针对每个环境的配置文件。

<included>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <target>System.out</target>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} |%t| [%p] %c %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="com.mijinco0612.springauth0" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <logger name="org.springframework" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>
    <logger name="org.apache.catalina" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

</included>
<included>
    <logger name="com.mijinco0612.springauth0" level="INFO" additivity="false">
        <appender-ref ref="FILE"/>
    </logger>

    <logger name="org.springframework" level="INFO" additivity="false">
        <appender-ref ref="FILE"/>
    </logger>
    <logger name="org.apache.catalina" level="INFO" additivity="false">
        <appender-ref ref="FILE"/>
    </logger>

</included>

我们应该如何进行切换?

在启动时准备每个不同的环境配置文件(yml),然后指定使用的配置。

application-local.yml
application-prd.yml

我创建了一个名为resources的目录。
由于此次的application.yml文件和配置值相同,因此目录内没有内容。

不妨试试看。


~/s/spring-auth0 ❯❯❯ mvn clean spring-boot:run -U -Dspring.profiles.active=local                                                                                                                   ✘ 10 
[INFO] Scanning for projects...
[INFO] 
[INFO] --------------------< com.mijinco0612:spring-auth0 >--------------------
[INFO] Building spring-auth0 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.0.0:clean (default-clean) @ spring-auth0 ---
[INFO] Deleting /Users/takamichi_tatsumoto/study-auth0/spring-auth0/target
[INFO] 
[INFO] >>> spring-boot-maven-plugin:2.0.3.RELEASE:run (default-cli) > test-compile @ spring-auth0 >>>
[INFO] 
[INFO] --- maven-resources-plugin:3.0.1:resources (default-resources) @ spring-auth0 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 3 resources
[INFO] Copying 3 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ spring-auth0 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /Users/takamichi_tatsumoto/study-auth0/spring-auth0/target/classes

====中略=====

2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 
2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 
2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 
2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 
2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 
2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 
2018-07-06 17:36:32 |main| [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'autoConfigurationReport' 

log以debug级别输出到标准输出。

~/s/spring-auth0 ❯❯❯ mvn clean spring-boot:run -U -Dspring.profiles.active=prd                                                                                                                     ✘ 10 
[INFO] Scanning for projects...
[INFO] 
[INFO] --------------------< com.mijinco0612:spring-auth0 >--------------------
[INFO] Building spring-auth0 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.0.0:clean (default-clean) @ spring-auth0 ---
[INFO] Deleting /Users/takamichi_tatsumoto/study-auth0/spring-auth0/target
[INFO] 
[INFO] >>> spring-boot-maven-plugin:2.0.3.RELEASE:run (default-cli) > test-compile @ spring-auth0 >>>
[INFO] 
[INFO] --- maven-resources-plugin:3.0.1:resources (default-resources) @ spring-auth0 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 3 resources
[INFO] Copying 3 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ spring-auth0 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /Users/takamichi_tatsumoto/study-auth0/spring-auth0/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.0.1:testResources (default-testResources) @ spring-auth0 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/takamichi_tatsumoto/study-auth0/spring-auth0/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ spring-auth0 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/takamichi_tatsumoto/study-auth0/spring-auth0/target/test-classes
[INFO] 
[INFO] <<< spring-boot-maven-plugin:2.0.3.RELEASE:run (default-cli) < test-compile @ spring-auth0 <<<
[INFO] 
[INFO] 
[INFO] --- spring-boot-maven-plugin:2.0.3.RELEASE:run (default-cli) @ spring-auth0 ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.3.RELEASE)

只有输出到标准输出的部分才到这里。

2018-07-06 17:39:09 |main| [INFO] org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@780de0b5: startup date [Fri Jul 06 17:39:09 JST 2018]; root of context hierarchy
2018-07-06 17:39:10 |main| [INFO] org.springframework.beans.factory.support.DefaultListableBeanFactory Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2018-07-06 17:39:11 |main| [INFO] org.springframework.boot.web.embedded.tomcat.TomcatWebServer Tomcat initialized with port(s): 28080 (http)
2018-07-06 17:39:12 |main| [INFO] org.apache.catalina.core.StandardService Starting service [Tomcat]
2018-07-06 17:39:12 |main| [INFO] org.apache.catalina.core.StandardEngine Starting Servlet Engine: Apache Tomcat/8.5.31
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.apache.catalina.core.AprLifecycleListener The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/takamichi_tatsumoto/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] Initializing Spring embedded WebApplicationContext
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.web.context.ContextLoader Root WebApplicationContext: initialization completed in 2344 ms
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.boot.web.servlet.FilterRegistrationBean Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.boot.web.servlet.FilterRegistrationBean Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.boot.web.servlet.FilterRegistrationBean Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.boot.web.servlet.FilterRegistrationBean Mapping filter: 'requestContextFilter' to: [/*]
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-07-06 17:39:12 |localhost-startStop-1| [INFO] org.springframework.boot.web.servlet.ServletRegistrationBean Servlet dispatcherServlet mapped to [/]
2018-07-06 17:39:13 |main| [INFO] org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration

Using generated security password: c876b0f9-5585-4694-bffc-7930fb15e2fb

2018-07-06 17:39:13 |main| [INFO] org.springframework.security.web.DefaultSecurityFilterChain Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@480e2604, org.springframework.security.web.context.SecurityContextPersistenceFilter@2845ab1b, org.springframework.security.web.header.HeaderWriterFilter@68d5c82d, org.springframework.security.web.authentication.logout.LogoutFilter@71691f65, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@32a29e56, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@1d5f0165, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@378e6eea, org.springframework.security.web.session.SessionManagementFilter@2ff8ec7b, org.springframework.security.web.access.ExceptionTranslationFilter@f408f00, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@2a688901]
2018-07-06 17:39:13 |main| [INFO] org.springframework.web.servlet.handler.SimpleUrlHandlerMapping Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-06 17:39:14 |main| [INFO] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@780de0b5: startup date [Fri Jul 06 17:39:09 JST 2018]; root of context hierarchy
2018-07-06 17:39:14 |main| [INFO] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping Mapped "{[/api/v1/public],methods=[GET]}" onto public java.lang.String com.mijinco0612.springauth0.controller.api.v1.DemoController.publicApi()
2018-07-06 17:39:14 |main| [INFO] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping Mapped "{[/api/v1/private],methods=[GET]}" onto public 

在logback.xml中指定的目录(/var/www/logs)下创建了一个名为spring-auth0.log的文件,并在该文件中输出了info级别的日志。

总结

可以实现日志记录的设置和根据不同的环境来输出。