Spring boot admin 日誌

前言

之前寫過Spring Boot Admin的使用教程,還配置了各類路徑參數。最近有留言說client的log怎麼查看,其實log這個沒寫是由於,不能知足性能與管理的須要,ELK技術很成熟,搜索也是,備份管理都有現成的,可是估計有些小公司不須要這樣的技術,只須要能夠快速查看的日誌入口就能夠了。下面來試試。java

1. SBA log示例

這次使用consul + admin + clientweb

1. 1 consul啓動

因爲個人電腦是macos,只須要./consul agent -dev便可,win更容易,直接雙擊啓動spring

1.2 admin server

pom依賴express

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-boot-admin</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>admin-derver</artifactId>

    <dependencies>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>
    </dependencies>
</project>

bootMain類macos

package com.feng.admin.server;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableAdminServer
@EnableDiscoveryClient
public class ServerMain {
    public static void main(String[] args) {
        SpringApplication.run(ServerMain.class, args);
    }
}

applicationapache

server.port=8082
spring.application.name=AdminServer


management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name}

1.3 admin client

client同理,複製AdminServer,便可去除<artifactId>spring-boot-admin-starter-server</artifactId>依賴便可,去除AdminServer註解,修改端口api

查看結果 緩存

2. client log改造

所謂的log實時查看是client提供一個讀取本地文件的接口,而後admin定時調用顯示,達到實時展現的效果。須要2步便可springboot

2.1 application增長

management.endpoint.logfile.external-file=/Users/huahua/logs/boot.log

還有其餘方式,後面說app

2.2 增長logback-spring.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="APP_Name" value="logback" />
       <contextName>${APP_Name}</contextName>
    <!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑,請根據需求配置路徑-->
    <property name="LOG_HOME" value="/Users/huahua/logs/" />

    <!-- 彩色日誌依賴的渲染類 -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    <!-- 彩色日誌格式 -->
    <property name="CONSOLE_LOG_PATTERN"
              value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(LN:%L){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />

    <!-- 控制檯輸出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <!-- 按照天天生成日誌文件 -->
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_HOME}/boot.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日誌文件輸出的文件名-->
            <FileNamePattern>${LOG_HOME}/boot-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日誌文件保留天數-->
            <MaxHistory>3</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}:%L - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.springframework.boot.actuate.endpoint.web.servlet" level="trace"/>

    <!-- 日誌輸出級別  ,注意:若是不寫<appender-ref ref="FILE" /> ,將致使springbootadmin找不到文件,沒法查看日誌 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

注意這個,必須爲trace,能夠打印actuator的HTTP requestmapping信息

<logger name="org.springframework.boot.actuate.endpoint.web.servlet" level="trace"/>

重點關注logfile接口,這個接口必須配置參數才能出現

2.3 效果以下

F12能夠看到,頁面在定時請求

3. 原理分析

根源在一個自動配置上

public class LogFile {
    public static final String FILE_NAME_PROPERTY = "logging.file.name";
    public static final String FILE_PATH_PROPERTY = "logging.file.path";



package org.springframework.boot.actuate.autoconfigure.logging;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.actuate.logging.LogFileWebEndpoint;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.logging.LogFile;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for {@link LogFileWebEndpoint}.
 *
 * @author Andy Wilkinson
 * @author Christian Carriere-Tisseur
 * @since 2.0.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnAvailableEndpoint(endpoint = LogFileWebEndpoint.class)
@EnableConfigurationProperties(LogFileWebEndpointProperties.class)
public class LogFileWebEndpointAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
    //條件式,很關鍵,默認條件是false
	@Conditional(LogFileCondition.class)
	public LogFileWebEndpoint logFileWebEndpoint(ObjectProvider<LogFile> logFile,
			LogFileWebEndpointProperties properties) {
		return new LogFileWebEndpoint(logFile.getIfAvailable(), properties.getExternalFile());
	}

	private static class LogFileCondition extends SpringBootCondition {

		@Override
        //條件斷定
		public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
			Environment environment = context.getEnvironment();
			String config = getLogFileConfig(environment, LogFile.FILE_NAME_PROPERTY);
			ConditionMessage.Builder message = ConditionMessage.forCondition("Log File");
			if (StringUtils.hasText(config)) {
				return ConditionOutcome.match(message.found(LogFile.FILE_NAME_PROPERTY).items(config));
			}
			config = getLogFileConfig(environment, LogFile.FILE_PATH_PROPERTY);
			if (StringUtils.hasText(config)) {
				return ConditionOutcome.match(message.found(LogFile.FILE_PATH_PROPERTY).items(config));
			}
			config = environment.getProperty("management.endpoint.logfile.external-file");
			if (StringUtils.hasText(config)) {
				return ConditionOutcome.match(message.found("management.endpoint.logfile.external-file").items(config));
			}
			return ConditionOutcome.noMatch(message.didNotFind("logging file").atAll());
		}

		private String getLogFileConfig(Environment environment, String configName) {
			return environment.resolvePlaceholders("${" + configName + ":}");
		}

	}

}

因此logging.file.name、logging.file.path、management.endpoint.logfile.external-file均可以開啓條件

logging.file.path配置要注意,這個是個坑,會默認spring.log的文件,logging.file.name不會

public String toString() {
        return StringUtils.hasLength(this.file) ? this.file : (new File(this.path, "spring.log")).getPath();
    }

另外能夠看到LogFileWebEndpointProperties這個配置

因此management.endpoint.logfile.externalFile也是能夠的,實際上

Spring在解析properties時會在Spring緩存的Map中,把management.endpoint.logfile.external-file的key會轉換成management.endpoint.logfile.externalFile。

 

最終的結果是實例化LogFileWebEndpoint,建立endpoint的requestmapping接口映射

/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.actuate.logging;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.boot.logging.LogFile;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * Web {@link Endpoint @Endpoint} that provides access to an application's log file.
 *
 * @author Johannes Edmeier
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @since 2.0.0
 */
@WebEndpoint(id = "logfile")
public class LogFileWebEndpoint {

	private static final Log logger = LogFactory.getLog(LogFileWebEndpoint.class);

	private File externalFile;

	private final LogFile logFile;

	public LogFileWebEndpoint(LogFile logFile, File externalFile) {
		this.externalFile = externalFile;
		this.logFile = logFile;
	}

	@ReadOperation(produces = "text/plain; charset=UTF-8")
    //最終是requestmapping,訪問這個方法,本質是讀取文件
	public Resource logFile() {
		Resource logFileResource = getLogFileResource();
		if (logFileResource == null || !logFileResource.isReadable()) {
			return null;
		}
		return logFileResource;
	}

	private Resource getLogFileResource() {
		if (this.externalFile != null) {
			return new FileSystemResource(this.externalFile);
		}
		if (this.logFile == null) {
			logger.debug("Missing 'logging.file.name' or 'logging.file.path' properties");
			return null;
		}
		return new FileSystemResource(this.logFile.toString());
	}

}

 

總結

其實Spring Boot Admin顯示client的日誌原理很簡單,client暴露HTTP,admin定時調用。client端取日誌須要配置才能開啓,是讀取本地文件。

源碼分析也驗證了上面的觀點。

相關文章
相關標籤/搜索