2025/03/31

SpringBoot3 - Spring Boot Log

spring 提供的 Logging :: Spring Boot 有以下幾種

name package
Java Util Logging spring-boot-starter-logging
Logback spring-boot-starter-logging
Log4j2 spring-boot-starter-log4j2

spring-boot-starter-logging 是預設引用的,所有 spring-boot-starter-* 都會引用 spring-boot-starter-logging。不需要自行引用。

spring-boot-starter-logging 使用 Commons Logging,支援 Java Util Logging、Log4j2、Logback

使用 starter 預設會使用 Logback,透過 logback 支援 Java Util Logging, Commons Logging, Log4J, or SLF4J。

Log Format

2024-11-15T17:25:40.765+08:00  INFO 4924 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
  • Date & Time

  • Log Level

  • Process ID

  • --- separator

  • [Application name] 如果有設定 spring.application.name 才會出現

  • [Thread name]

  • Correlation ID 如果有設定 tracing 才會出現

  • Logger name 通常是來源 class name 的縮寫

  • log message

Console Output

預設會出現 ERROR-level, WARN-level, and INFO-level messages

如果在 CLI 有加上 java -jar Demo1.jar --debug debug flag,就會出現 core loggers (embedded container, Hibernate, and Spring Boot) 更多的資訊。這邊不代表 application 的 DEBUG level message 會出現

CLI 也可以加上 --trace ,會增加 core logger 資訊


Color-coded Output

terminal 有支援 ANSI 時,就可以增加顏色

ex: %clr(%5p)

Level Color
FATAL Red
ERROR Red
WARN Yellow
INFO Green
DEBUG Green
TRACE Green

可以自訂顏色

  • blue

  • cyan

  • faint

  • green

  • magenta

  • red

  • yellow

ex: %clr(%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}){yellow}

File Output

spring boot 預設只會寫入 console log

要寫入 file log 必須設定 logging.file.namelogging.file.path,兩個都設定時,只會使用 logging.file.name。log file rotate 預設為 10M,log level 跟 console 一樣,會寫入 ERROR, WARN, INFO level

File Rotation

調整 log rotate 規則

要修改 application.properties(yaml),如果是 log4j 就要設定 log4j2.xml or log4j2-spring.xml

name desc
logging.logback.rollingpolicy.file-name-pattern filename pattern
logging.logback.rollingpolicy.clean-history-on-start 在 application 啟動時,要做 log cleanup
logging.logback.rollingpolicy.max-file-size logfile 的最大 size
logging.logback.rollingpolicy.total-size-cap log archives 刪除前的最大 size
logging.logback.rollingpolicy.max-history archive log files 保留幾個(default: 7)

Log Level

logging.level.<logger-name>=<level>

為 TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF 其中一個

logging.level.root 是設定 root logger

logging:
  level:
    root: "warn"
    org.springframework.web: "debug"
    org.hibernate: "error"

也可以設定環境變數,ex:

LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG

Log Groups

ex: 一次設定所有 tomcat 相關的 logger level,group 合併後,再設定 level

在 applicaiton.yaml

logging:
  group:
    tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat"

logging:
  level:
    tomcat: "trace"

spring pre-defined logging groups

name loggers
web org.springframework.core.codec, org.springframework.http, org.springframework.web, org.springframework.boot.actuate.endpoint.web, org.springframework.boot.web.servlet.ServletContextInitializerBeans
sql org.springframework.jdbc.core, org.hibernate.SQL, org.jooq.tools.LoggerListener

Log Shutdown hook

要在 application 關閉前,release logging resource,要在 JVM exits 時,加上 shutdown hook

使用 jar 時,shutdown hook 會自動註冊

如要關閉 shutdown hook

logging:
  register-shutdown-hook: false

Custom Log Configuration

logging.config 決定 logging framework,然後就能使用該 framework 的設定檔

Logging System Customization
Logback logback-spring.xmllogback-spring.groovylogback.xml, or logback.groovy
Log4j2 log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging) logging.properties

建議使用 logback-spring.xml,不要用 logback.xml,spring 可能會無法控制 log 初始化

以下設定參數,可轉換為環境變數

Spring Environment System Property Comments
logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD The conversion word used when logging exceptions.
logging.file.name LOG_FILE If defined, it is used in the default log configuration.
logging.file.path LOG_PATH If defined, it is used in the default log configuration.
logging.pattern.console CONSOLE_LOG_PATTERN The log pattern to use on the console (stdout).
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Appender pattern for log date format.
logging.charset.console CONSOLE_LOG_CHARSET The charset to use for console logging.
logging.threshold.console CONSOLE_LOG_THRESHOLD The log level threshold to use for console logging.
logging.pattern.file FILE_LOG_PATTERN The log pattern to use in a file (if LOG_FILE is enabled).
logging.charset.file FILE_LOG_CHARSET The charset to use for file logging (if LOG_FILE is enabled).
logging.threshold.file FILE_LOG_THRESHOLD The log level threshold to use for file logging.
logging.pattern.level LOG_LEVEL_PATTERN The format to use when rendering the log level (default %5p).
PID PID

使用 logback,可多使用這些參數

Spring Environment System Property Comments
logging.logback.rollingpolicy.file-name-pattern LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN Pattern for rolled-over log file names (default ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz).
logging.logback.rollingpolicy.clean-history-on-start LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START Whether to clean the archive log files on startup.
logging.logback.rollingpolicy.max-file-size LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE Maximum log file size.
logging.logback.rollingpolicy.total-size-cap LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP Total size of log backups to be kept.
logging.logback.rollingpolicy.max-history LOGBACK_ROLLINGPOLICY_MAX_HISTORY

Logback Extension

logback-spring.xml 裡面有幾個 logback extensions

profile-specific cofiguration

根據 active profile,<springProfile> 可 include/exclude 部分設定

<springProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>

<springProfile name="dev | staging">
    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>

<springProfile name="!production">
    <!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>

environment properties

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>

example

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOG_PATH" value="/var/log/blog"/>
    <property name="LOG_FILENAME" value="spring-profiles"/>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

    <springProfile name="default,ide">
        <root level="INFO">
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

    <springProfile name="test,prod">
        <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <encoder>
                <pattern>${FILE_LOG_PATTERN}</pattern>
            </encoder>
            <file>${LOG_PATH}/${LOG_FILENAME}.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                <fileNamePattern>${LOG_PATH}/${LOG_FILENAME}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <maxHistory>7</maxHistory>
                <maxFileSize>100MB</maxFileSize>
                <totalSizeCap>1GB</totalSizeCap>
            </rollingPolicy>
        </appender>

        <root level="INFO">
            <appender-ref ref="FILE"/>
        </root>
    </springProfile>

</configuration>

Log4j2 Extension

可在 log4j2-spring.xml 設定使用

profile-specific configuration

<SpringProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
</SpringProfile>

<SpringProfile name="dev | staging">
    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</SpringProfile>

<SpringProfile name="!production">
    <!-- configuration to be enabled when the "production" profile is not active -->
</SpringProfile> 

Environment Properties Lookup

<Properties>
    <Property name="applicationName">${spring:spring.application.name}</Property>
</Properties>

log4j2 system properties

ex: ConsoleAppender 在 windows 使用 Jansi

log4j2.skipJansi=false

沒有留言:

張貼留言