5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Bootにおけるlog設定(環境毎の出し分け)

Last updated at Posted at 2018-07-06

## 動機

  • spring-bootアプリケーションのlogを残したいな。
  • 環境ごとに出力を変えたい
    • 本番ならば特定のディレクトリにファイルでlogLevelはinfoかな
    • ローカルならば標準出力にlogLevelはdebugかな

リポジトリ

以前作ったここを流用します:https://github.com/mijinco0612-self-improvement/spring-auth0

##やってみる

先ずはpomにdependencyを追加

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

出力するだけであればlogbackのみでOK。
環境毎に設定を変える場合janinoが必要です。

resourcesディレクトリにlogback.xmlを追加

logback.xml
<?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ディレクトリに環境毎の設定ファイルを作成します。

local.xml(ローカル環境用)
<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>
prd.xml(本番環境用)
<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>

切り替えはどうするのか?

環境ごとのprofile(yml)を用意して起動時に指定します。

application-local.yml
application-prd.yml

をresourcesディレクトリに作成しました。
今回はapplicaiton.ymlと設定値に違いがないため中身は空のままとしています。

試してみよう。

localプロファイルを指定した場合

~/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' 

標準出力にdebug levelでlogが出力されています。

prdプロファイルを指定した場合
~/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)

標準出力に出力されるのはここまで

tail-f/var/www/logs/spring-auth0.log
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 levelのlogが出力されています。

まとめ

log出力の設定と環境毎の出し分けが実現できました。

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?