Spring Boot日誌集成實戰

Spring Boot日誌框架

Spring Boot支持Java Util Logging,Log4j2,Lockback做爲日誌框架,若是你使用starters啓動器,Spring Boot將使用Logback做爲默認日誌框架。不管使用哪一種日誌框架,Spring Boot都支持配置將日誌輸出到控制檯或者文件中。java

spring-boot-starter啓動器包含spring-boot-starter-logging啓動器並集成了slf4j日誌抽象及Logback日誌框架。web

屬性配置日誌

Spring Boot支持屬性配置日誌參數,這個不是很靈活,不細講。spring

參考配置:sql

# LOGGING
logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name. For instance `myapp.log`
logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
logging.path= # Location of the log file. For instance `/var/log`
logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.

如:apache

logging.level.root=DEBUG
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

自定義日誌文件

根據不一樣的日誌框架,默認加載的日誌配置文件的文件名,放在資源根目錄下,其餘的目錄及文件名不能被加載。bootstrap

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

既然默認自帶了Logback框架,Logback也是最優秀的日誌框架,往資源目錄下建立一個logback-spring.xml便可,下面是一個參考配置文件。微信

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

	<springProperty scope="context" name="APP_NAME" source="spring.application.name"/>
	<springProperty scope="context" name="APP_PORT" source="server.port"/>
	<springProperty scope="context" name="DEFAULT_APP_PORT" source="spring.application.port"/>

	<property name="OS_NAME" value="${os.name}"/>
	<if condition='property("OS_NAME").contains("Windows")'>
		<then>
			<property name="LOG_PATH" value="${LOG_PATH:-E:/logs}" />
		</then>
		<else>
			<property name="LOG_PATH" value="${LOG_PATH:-/log}" />
		</else>
	</if>    	
    
	<property name="APP_NAME" value="${APP_NAME:-system}" />
	<property name="APP_PORT" value="${APP_PORT:-${DEFAULT_APP_PORT}}" />
	
	<!-- 控制檯輸出 -->
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度,%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</encoder>
	</appender>
	
	<!-- 按照天天生成日誌文件 -->
	<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--日誌文件輸出的文件名 -->
			<FileNamePattern>${LOG_PATH}/${APP_NAME}-${APP_PORT}/info.log.%d{yyyy-MM-dd}.log</FileNamePattern>
			
			<!--日誌文件保留天數 -->
			<MaxHistory>30</MaxHistory>
		</rollingPolicy>
		
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</encoder>
		
		<!--日誌文件最大的大小 -->
		<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
			<MaxFileSize>10MB</MaxFileSize>
		</triggeringPolicy>
		
	</appender>
	
	<!-- 按照天天生成日誌文件 error級別 -->
	<appender name="FILE-ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>ERROR</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>   
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--日誌文件輸出的文件名 -->
			<FileNamePattern>${LOG_PATH}/${APP_NAME}-${APP_PORT}/error.log.%d{yyyy-MM-dd}.log</FileNamePattern>
			
			<!--日誌文件保留天數 -->
			<MaxHistory>30</MaxHistory>
		</rollingPolicy>
		
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符 -->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</encoder>
		
		<!--日誌文件最大的大小 -->
		<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
			<MaxFileSize>10MB</MaxFileSize>
		</triggeringPolicy>
		
	</appender>

	<!--myibatis log configure -->
	<logger name="com.apache.ibatis" level="TRACE" />
	<logger name="java.sql.Connection" level="DEBUG" />
	<logger name="java.sql.Statement" level="DEBUG" />
	<logger name="java.sql.PreparedStatement" level="DEBUG" />

	<!-- 日誌輸出級別 -->
	<root level="INFO">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
		<appender-ref ref="FILE-ERROR" />
	</root>
	
</configuration>

強烈推薦使用logback-spring.xml做爲文件名,由於logback.xml加載太早。app

日誌初始化在ApplicationContext建立以前,因此@PropertySources加載的配置是讀取不到的,系統環境變量、Spring Environment及application,bootstrap配置文件中的信息能夠讀取到。框架

讀取系統環境屬性:spring-boot

<property name="LOG_PATH" value="${LOG_PATH:-E:/logs}" />

讀取當前應用Environment中的屬性:

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>

Spring Boot也支持經過springProfile來加載不一樣profiles下的配置。

<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>

推薦:Spring Boot & Cloud 最強技術教程

掃描關注咱們的微信公衆號,乾貨天天更新。

image

相關文章
相關標籤/搜索