0
0

More than 1 year has passed since last update.

Spring Bootとlogback-accessでTomcatのアクセスログを出力

Posted at

Spring BootでTomcatのアクセスログを出力するにはserver.tomcat.accesslog.*プロパティを使用するが、これで不足する場合にはlogback-accessを使用する。設定はlogback-access-spring-boot-starterの依存性追加するのが簡単で、ここではこのstarterを使わずに同等の設定をする方法をメモしておく。内部的にはstarterと同等の事をやっている。

まずlogback-accessの依存性を追加する。

plugins {
  id 'java'
  id 'org.springframework.boot' version '3.0.5'
  id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'

  implementation 'ch.qos.logback:logback-access'
}

tasks.named('test') {
  useJUnitPlatform()
}

以下のようにlogback-accessの設定を追加する。アクセスログ用のlogback設定ファイルは後述で、デフォルトのファイル名はconf/logback-access.xmlなので下記コメント行のように変更できる。

import org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ch.qos.logback.access.tomcat.LogbackValve;

@Configuration
public class LogbackAccessConfig {

  @Bean
  public WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory> webServerFactoryCustomizer() {
    return (factory) -> {
      LogbackValve v = new LogbackValve();
      // v.setFilename(new ClassPathResource("logback-access.xml").getPath());
      factory.addEngineValves(v);
    };
  }
}

src/main/resources/conf/logback-access.xmlにアクセスログ用の設定ファイルを配置する。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <Pattern>combined</Pattern>
      <Pattern>[ACCESS] %h %l %u %r %t{yyyy-MM-dd HH:mm:ss.SSS} %s %b %D ms</Pattern>
    </encoder>
  </appender>

  <appender-ref ref="STDOUT" />
</configuration>

こうすると以下のようなアクセスログが表示される。

[ACCESS] 0:0:0:0:0:0:0:1 - - GET /hoge HTTP/1.1 2023-04-11 18:23:05.002 404 275 24 ms
0
0
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
0
0