0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WSL上のDockerコンテナからホストマシンにアプリログを出力する。

Posted at

ローカルのDockerコンテナ上で動いているSpring bootのアプリログを、コンソールではなくファイルに出力したかったのですが、なかなか設定が上手くいかなかったので備忘として残しておきます。

環境

バージョン
OS Windows 10
WSL 2.2.4.0
Docker 26.1.3
docker-compose 1.25.0
Spring Boot 3.3.1

設定

logbackの設定とdocker-compose.yamlの設定をしていきます。

logback-spring.xml

locaback-spring.xmlにはログファイルの出力先を設定していきます。

src/main/resouces/locback-spring.xml
<configuration>
    <!-- 出力先とファイル名 -->
    <property name="directory" value="log" />
    <property name="fileName" value="app.log" />

    <appender name="FILE"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${directory}/${fileName}</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${directory}/${fileName}-%d{yyyy-MM-dd}.log</fileNamePattern>

            <maxHistory>10</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
        <!-- ファイルにも書き出すようにする -->
        <appender-ref ref="FILE" />
    </root>
</configuration>

今回は説明を簡略化するため、プロファイルによる出力先やログレベルの切り替えはしていません。

docker-compose.yaml

docker-compose.yamlにはログファイルの出力先と、ホストマシンのディレクトリをリンクさせるためにvolumesを指定します。

docker-compose.yaml
version: '3'
services:
  app:
    image: eclipse-temurin:21
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - JAR_FILE=build/libs/*.jar
    ports:
      - "8080:8080"
    entrypoint: ["java","-jar","/app.jar"]
    volumes:
      - ./build/libs:/build/libs
      - /mnt/c/log:/log     # これを追加する

DockerFile

念のため、今回使用したDockerFileも記載しておきます。

FROM eclipse-temurin:21
ARG JAR_FILE=build/libs/\*.jar -t springio/gs-spring-boot-docker .
COPY build/libs/OutputSpringLogOnDocker-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]

まとめ

ローカルで動かす時は普段はコンソールで確認していたので気にしていませんでしたが、ファイルとして出力するとなると意外に苦労しました。
volumeの指定がWindowsのパスではなく、WSLのパスにする必要があることに気づけばすぐだったのですが・・・。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?