Spring Boot Log4j2 - Spring Boot 168 EP 7

Spring Boot Log4j2 – Spring Boot 168 EP 7

可以替換預設所使用的 Logging 日誌框架,同樣也支援各種級別的日誌, EP 7 增加了相依套件,並排除 Logging 套件。

前言

Logging 是一個日誌框架,提供日常的開發,測試和生產環境中,記錄了應用,服務運行過程中的訊息,以及出現異常時的例外,這些資訊常常作為查詢,定位,解決問題的關鍵。

Spring Boot Log4j2

檔案目錄

./
   +- build.gradle
   |   +- src
   |       +- main
   |           +- resources
   |           |   +- application.properties
   |           |   +- log4j2.xml
   +- logs
       +- spring-boot-168.log    

Gradle

build.gradle

增加 Log4j2 ,並排除預設 Logging 。

修改完後,點右鍵,Gradle -> Refresh Gradle Project 。

buildscript {
	group 'org.ruoxue.spring-boot-168'
	version = '0.0.1-SNAPSHOT'
	ext {
            springBootVersion = '2.1.7.RELEASE'
	}
}

configurations.all {
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

dependencies {
    implementation "org.springframework.boot:spring-boot-starter-log4j2:${springBootVersion}"
}

設定

log4j2.xml

新增檔案,增加以下配置。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
	<Properties>
		<Property name="LOG_PATTERN"
			value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} [%thread] %p %c{1}#%M:%L - %m%n%ex" />
		<Property name="LOG_PATH">logs</Property>
		<Property name="LOG_FILE">spring-boot-168</Property>
	</Properties>

	<Appenders>
		<Console name="ConsoleAppender" target="SYSTEM_OUT"
			follow="true">
			<PatternLayout pattern="${LOG_PATTERN}" />
		</Console>

		<RollingRandomAccessFile name="FileAppender"
			fileName="${LOG_PATH}/${LOG_FILE}.log"
			filePattern="${LOG_PATH}/${LOG_FILE}-%d{yyyy-MM-dd}-%i.log.gz">
			<PatternLayout>
				<Pattern>${LOG_PATTERN}</Pattern>
			</PatternLayout>
			<Policies>
				<TimeBasedTriggeringPolicy />
				<SizeBasedTriggeringPolicy size="100 MB" />
			</Policies>
			<DefaultRolloverStrategy max="10" />
		</RollingRandomAccessFile>
	</Appenders>

	<Loggers>
		<Root level="INFO">
			<AppenderRef ref="ConsoleAppender" level="INFO" />
			<AppenderRef ref="FileAppender" level="INFO" />
		</Root>

		<Logger name="org.springframework.jdbc" level="INFO"
			additivity="false">
			<Appender-Ref ref="ConsoleAppender" />
		</Logger>
	</Loggers>
</Configuration>

application.properties

增加 Logging 設定。

logging.config=classpath:log4j2.xml
spring.output.ansi.enabled=DETECT

測試

Application.main

在主程式點右鍵執行 Run As -> Java Application,查看 console,Server 已成功啟動,監聽 10000 port,並在此目錄下輸出成檔案, logs/spring-boot-168.log。

Spring Boot Web 執行主程式
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

[GC (Metadata GC Threshold)  141007K->15444K(1005056K), 0.0087456 secs]
[Full GC (Metadata GC Threshold)  15444K->14778K(1005056K), 0.0248207 secs]
2022-04-21T21:14:10.043+0800 INFO Application#logStarting:50 - Starting Application on cheng-pc with PID 2268 (D:\dev\gitlab\ruoxue\spring-boot-168\bin\main started by cheng in D:\dev\gitlab\ruoxue\spring-boot-168)
2022-04-21T21:14:10.048+0800 INFO Application#logStartupProfileInfo:647 - No active profile set, falling back to default profiles: default
2022-04-21T21:14:10.859+0800 INFO JettyServletWebServerFactory#getWebServer:143 - Server initialized with port: 10000
2022-04-21T21:14:10.861+0800 INFO Server#doStart:370 - jetty-9.4.19.v20190610; built: 2019-06-10T16:30:51.723Z; git: afcf563148970e98786327af5e07c261fda175d3; jvm 1.8.0_241-b07
2022-04-21T21:14:10.881+0800 INFO application#log:2351 - Initializing Spring embedded WebApplicationContext
2022-04-21T21:14:10.883+0800 INFO ContextLoader#prepareWebApplicationContext:284 - Root WebApplicationContext: initialization completed in 804 ms
2022-04-21T21:14:10.958+0800 INFO session#doStart:365 - DefaultSessionIdManager workerName=node0
2022-04-21T21:14:10.958+0800 INFO session#doStart:370 - No SessionScavenger set, using defaults
2022-04-21T21:14:10.959+0800 INFO session#startScavenging:149 - node0 Scavenging every 660000ms
2022-04-21T21:14:10.981+0800 INFO application#log:2351 - Warning: No org.apache.tomcat.JarScanner set in ServletContext. Falling back to default JarScanner implementation.
2022-04-21T21:14:11.055+0800 INFO TldScanner#info:119 - At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2022-04-21T21:14:11.059+0800 INFO ContextHandler#doStart:857 - Started o.s.b.w.e.j.JettyEmbeddedWebAppContext@7207cb51{application,/,[file:///C:/Users/cheng/AppData/Local/Temp/jetty-docbase.7613373992670349716.10000/],AVAILABLE}
2022-04-21T21:14:11.059+0800 INFO Server#doStart:410 - Started @3229ms
[GC (Metadata GC Threshold)  197288K->32587K(1005056K), 0.0112658 secs]
[Full GC (Metadata GC Threshold)  32587K->23414K(1005056K), 0.0249565 secs]
2022-04-21T21:14:11.216+0800 INFO ThreadPoolTaskExecutor#initialize:171 - Initializing ExecutorService 'applicationTaskExecutor'
2022-04-21T21:14:11.333+0800 INFO application#log:2351 - Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-21T21:14:11.333+0800 INFO DispatcherServlet#initServletBean:524 - Initializing Servlet 'dispatcherServlet'
2022-04-21T21:14:11.337+0800 INFO DispatcherServlet#initServletBean:546 - Completed initialization in 4 ms
2022-04-21T21:14:11.423+0800 INFO AbstractConnector#doStart:292 - Started ServerConnector@155d1021{HTTP/1.1,[http/1.1]}{0.0.0.0:10000}
2022-04-21T21:14:11.424+0800 INFO JettyWebServer#start:156 - Jetty started on port(s) 10000 (http/1.1) with context path '/'
2022-04-21T21:14:11.426+0800 INFO Application#logStarted:59 - Started Application in 1.665 seconds (JVM running for 3.595)    

心得分享

開發或維運時,當系統運行發生異常,往往最先查找的就是 log,一個良好易於管理的日誌系統,是不可或缺的一部份。

發佈留言