Spring Boot Actuator:健康檢查注簿、審計诡渴、統(tǒng)計和監(jiān)控

Spring Boot Actuator可以幫助你監(jiān)控和管理Spring Boot應(yīng)用玩徊,比如健康檢查恩袱、審計畔塔、統(tǒng)計和HTTP追蹤等。所有的這些特性可以通過JMX或者HTTP endpoints來獲得谅辣。

Actuator同時還可以與外部應(yīng)用監(jiān)控系統(tǒng)整合婶恼,比如 Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic等蚣录。這些系統(tǒng)提供了非常好的儀表盤萎河、圖標(biāo)虐杯、分析和告警等功能厦幅,使得你可以通過統(tǒng)一的接口輕松的監(jiān)控和管理你的應(yīng)用。

Actuator使用Micrometer來整合上面提到的外部應(yīng)用監(jiān)控系統(tǒng)瓤的。這使得只要通過非常小的配置就可以集成任何應(yīng)用監(jiān)控系統(tǒng)圈膏。

我將把Spring Boot Actuator教程分為兩部分:

  • 第一部分(本文)教你如何配置Actuator和通過Http endpoints來進入這些特征稽坤。
  • 第二部分教你如何整合Actuator和外部應(yīng)用監(jiān)控系統(tǒng)尿褪。

創(chuàng)建一個有Actuator的Spring Boot工程

首先讓我們建一個依賴acutator的簡單應(yīng)用顿仇。

你可以使用Spring Boot CLI創(chuàng)建應(yīng)用:

spring init -d=web,actuator -n=actuator actuator

或者臼闻,你可以使用Spring Initializr網(wǎng)站來創(chuàng)建應(yīng)用:

Spring initialzr.png

增加Spring Boot Actuator到一個存在的應(yīng)用

你可以增加spring-boot-actuator模塊到一個已經(jīng)存在的應(yīng)用,通過使用下面的依賴乓搬。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

對于Gradle缤谎,依賴如下:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-actuator")
}

使用Actuator Endpoints來監(jiān)控應(yīng)用

Actuator創(chuàng)建了所謂的endpoint來暴露HTTP或者JMX來監(jiān)控和管理應(yīng)用。

舉個例子频敛,有一個叫/health的endpoint斟赚,提供了關(guān)于應(yīng)用健康的基礎(chǔ)信息拗军。/metricsendpoints展示了幾個有用的度量信息发侵,比如JVM內(nèi)存使用情況刃鳄、系統(tǒng)CPU使用情況叔锐、打開的文件等等愉烙。/loggersendpoint展示了應(yīng)用的日志和可以讓你在運行時改變?nèi)罩镜燃墶?/p>

值得注意的是催植,每一給actuator endpoint可以被顯式的打開和關(guān)閉创南。此外稿辙,這些endpoints也需要通過HTTP或者JMX暴露出來邻储,使得它們能被遠(yuǎn)程進入旧噪。

讓我們運行應(yīng)用并且嘗試進入默認(rèn)通過HTTP暴露的打開狀態(tài)的actuator endpoints吨娜。之后,我們將學(xué)習(xí)如何打開更多的endpoints并且通過HTTP暴露它們淘钟。

在應(yīng)用的根目錄下打開命令行工具運行以下命令:

mvn spring-boot:run

應(yīng)用默認(rèn)使用8080端口運行宦赠。一旦這個應(yīng)用啟動了,你可以通過http://localhost:8080/actuator來展示所有通過HTTP暴露的endpoints米母。

{"_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"info":{"href":"http://localhost:8080/actuator/info","templated":false}}}

打開http://localhost:8080/actuator/health勾扭,則會顯示如下內(nèi)容:

{"status":"UP"}

狀態(tài)將是UP只要應(yīng)用是健康的。如果應(yīng)用不健康將會顯示DOWN,比如與儀表盤的連接異程鳎或者缺水磁盤空間等身辨。下一節(jié)我們將學(xué)習(xí)spring boot如何決定應(yīng)用的健康和如何修復(fù)這些健康問題。

infoendpoint(http://localhost:8080/actuator/info)展示了關(guān)于應(yīng)用的一般信息洗贰,這些信息從編譯文件比如META-INF/build-info.properties或者Git文件比如git.properties或者任何環(huán)境的property中獲取绎晃。你將在下一節(jié)中學(xué)習(xí)如何改變這個endpoint的輸出咱揍。

默認(rèn)硼砰,只有healthinfo通過HTTP暴露了出來遍愿。這也是為什么/actuator頁面只展示了healthinfoendpoints坞笙。我們將學(xué)習(xí)如何暴露其他的endpoint。首先,讓我們看看其他的endpoints是什么。

以下是一些非常有用的actuator endpoints列表午磁。你可以在official documentation上面看到完整的列表。

Endpoint ID Description
auditevents 顯示應(yīng)用暴露的審計事件 (比如認(rèn)證進入挺据、訂單失敗)
info 顯示應(yīng)用的基本信息
health 顯示應(yīng)用的健康狀態(tài)
metrics 顯示應(yīng)用多樣的度量信息
loggers 顯示和修改配置的loggers
logfile 返回log file中的內(nèi)容(如果logging.file或者logging.path被設(shè)置)
httptrace 顯示HTTP足跡块仆,最近100個HTTP request/repsponse
env 顯示當(dāng)前的環(huán)境特性
flyway 顯示數(shù)據(jù)庫遷移路徑的詳細(xì)信息
liquidbase 顯示Liquibase 數(shù)據(jù)庫遷移的纖細(xì)信息
shutdown 讓你逐步關(guān)閉應(yīng)用
mappings 顯示所有的@RequestMapping路徑
scheduledtasks 顯示應(yīng)用中的調(diào)度任務(wù)
threaddump 執(zhí)行一個線程dump
heapdump 返回一個GZip壓縮的JVM堆dump

打開和關(guān)閉Actuator Endpoints

默認(rèn)绷雏,上述所有的endpints都是打開的,除了shutdown endpoint缺前。

你可以通過設(shè)置management.endpoint.<id>.enabled to true or false(id是endpoint的id)來決定打開還是關(guān)閉一個actuator endpoint逝段。

舉個例子,要想打開shutdown endpoint,增加以下內(nèi)容在你的application.properties文件中:

management.endpoint.shutdown.enabled=true

暴露Actuator Endpoints

默認(rèn),素偶偶的actuator endpoint通過JMX被暴露拐袜,而通過HTTP暴露的只有healthinfo较解。

以下是你可以通過應(yīng)用的properties可以通過HTTP和JMX暴露的actuator endpoint。

  • 通過HTTP暴露Actuator endpoints勿她。

    # Use "*" to expose all endpoints, or a comma-separated list to expose selected ones
    management.endpoints.web.exposure.include=health,info 
    management.endpoints.web.exposure.exclude=
    
  • 通過JMX暴露Actuator endpoints玻蝌。

    # Use "*" to expose all endpoints, or a comma-separated list to expose selected ones
    management.endpoints.jmx.exposure.include=*
    management.endpoints.jmx.exposure.exclude=
    

通過設(shè)置management.endpoints.web.exposure.include*,我們可以在http://localhost:8080/actuator頁面看到如下內(nèi)容爆惧。

{"_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"auditevents":{"href":"http://localhost:8080/actuator/auditevents","templated":false},"beans":{"href":"http://localhost:8080/actuator/beans","templated":false},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"conditions":{"href":"http://localhost:8080/actuator/conditions","templated":false},"configprops":{"href":"http://localhost:8080/actuator/configprops","templated":false},"env":{"href":"http://localhost:8080/actuator/env","templated":false},"env-toMatch":{"href":"http://localhost:8080/actuator/env/{toMatch}","templated":true},"info":{"href":"http://localhost:8080/actuator/info","templated":false},"loggers":{"href":"http://localhost:8080/actuator/loggers","templated":false},"loggers-name":{"href":"http://localhost:8080/actuator/loggers/{name}","templated":true},"heapdump":{"href":"http://localhost:8080/actuator/heapdump","templated":false},"threaddump":{"href":"http://localhost:8080/actuator/threaddump","templated":false},"prometheus":{"href":"http://localhost:8080/actuator/prometheus","templated":false},"metrics-requiredMetricName":{"href":"http://localhost:8080/actuator/metrics/{requiredMetricName}","templated":true},"metrics":{"href":"http://localhost:8080/actuator/metrics","templated":false},"scheduledtasks":{"href":"http://localhost:8080/actuator/scheduledtasks","templated":false},"httptrace":{"href":"http://localhost:8080/actuator/httptrace","templated":false},"mappings":{"href":"http://localhost:8080/actuator/mappings","templated":false}}}

解析常用的actuator endpoint

/health endpoint

health endpoint通過合并幾個健康指數(shù)檢查應(yīng)用的健康情況绢要。

Spring Boot Actuator有幾個預(yù)定義的健康指標(biāo)比如DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator, RedisHealthIndicator, CassandraHealthIndicator等盏筐。它使用這些健康指標(biāo)作為健康檢查的一部分纳令。

舉個例子纬傲,如果你的應(yīng)用使用Redis摔竿,RedisHealthindicator將被當(dāng)作檢查的一部分柄驻。如果使用MongoDB,那么MongoHealthIndicator將被當(dāng)作檢查的一部分态兴。

你也可以關(guān)閉特定的健康檢查指標(biāo)章贞,比如在prpperties中使用如下命令:

management.health.mongo.enabled=false

默認(rèn),所有的這些健康指標(biāo)被當(dāng)作健康檢查的一部分。

顯示詳細(xì)的健康信息

health endpoint只展示了簡單的UPDOWN狀態(tài)。為了獲得健康檢查中所有指標(biāo)的詳細(xì)信息,你可以通過在application.yaml中增加如下內(nèi)容:

management:
  endpoint:
    health:
      show-details: always

一旦你打開上述開關(guān),你在/health中可以看到如下詳細(xì)內(nèi)容:

{"status":"UP","details":{"diskSpace":{"status":"UP","details":{"total":250790436864,"free":27172782080,"threshold":10485760}}}}

health endpoint現(xiàn)在包含了DiskSpaceHealthIndicator

如果你的應(yīng)用包含database(比如MySQL)吹缔,health endpoint將顯示如下內(nèi)容:

{
   "status":"UP",
   "details":{
      "db":{
         "status":"UP",
         "details":{
            "database":"MySQL",
            "hello":1
         }
      },
      "diskSpace":{
         "status":"UP",
         "details":{
            "total":250790436864,
            "free":100330897408,
            "threshold":10485760
         }
      }
   }
}

如果你的MySQL server沒有啟起來,狀態(tài)將會變成DOWN

{
   "status":"DOWN",
   "details":{
      "db":{
         "status":"DOWN",
         "details":{
            "error":"org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30006ms."
         }
      },
      "diskSpace":{
         "status":"UP",
         "details":{
            "total":250790436864,
            "free":100324585472,
            "threshold":10485760
         }
      }
   }
}

創(chuàng)建一個自定義的健康指標(biāo)

你可以通過實現(xiàn)HealthIndicator接口來自定義一個健康指標(biāo)芋类,或者繼承AbstractHealthIndicator類。

package com.example.actuator.health;

import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator extends AbstractHealthIndicator {

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        // Use the builder to build the health status details that should be reported.
        // If you throw an exception, the status will be DOWN with the exception message.
        
        builder.up()
                .withDetail("app", "Alive and Kicking")
                .withDetail("error", "Nothing! I'm good.");
    }
}

一旦你增加上面的健康指標(biāo)到你的應(yīng)用中去后导街,health endpoint將展示如下細(xì)節(jié):

{
   "status":"UP",
   "details":{
      "custom":{
         "status":"UP",
         "details":{
            "app":"Alive and Kicking",
            "error":"Nothing! I'm good."
         }
      },
      "diskSpace":{
         "status":"UP",
         "details":{
            "total":250790436864,
            "free":97949245440,
            "threshold":10485760
         }
      }
   }
}

/metrics endpoint

metrics endpoint展示了你可以追蹤的所有的度量误堡。

{
    "names": [
        "jvm.memory.max",
        "http.server.requests",
        "process.files.max",
        ...
        "tomcat.threads.busy",
        "process.start.time",
        "tomcat.servlet.error"
    ]
}

想要獲得每個度量的詳細(xì)信息沾谜,你需要傳遞度量的名稱到URL中,像

http://localhost:8080/actuator/metrics/{MetricName}

舉個例子,獲得systems.cpu.usage的詳細(xì)信息赘那,使用以下URLhttp://localhost:8080/actuator/metrics/system.cpu.usage。它將顯示如下內(nèi)容:

{
    "name": "system.cpu.usage",
    "measurements": [
    {
        "statistic": "VALUE",
        "value": 0
    }
    ],
"availableTags": []
}

/loggers endpoint

loggers endpoint,可以通過訪問http://localhost:8080/actuator/loggers來進入嗅义。它展示了應(yīng)用中可配置的loggers的列表和相關(guān)的日志等級。

你同樣能夠使用http://localhost:8080/actuator/loggers/{name}來展示特定logger的細(xì)節(jié)季希。

舉個例子褪那,為了獲得root logger的細(xì)節(jié)幽纷,你可以使用http://localhost:8080/actuator/loggers/root

{
   "configuredLevel":"INFO",
   "effectiveLevel":"INFO"
}

在運行時改變?nèi)罩镜燃?/h4>

loggers endpoint也允許你在運行時改變應(yīng)用的日志等級。

舉個例子博敬,為了改變root logger的等級為DEBUG 友浸,發(fā)送一個POST請求到http://localhost:8080/actuator/loggers/root,加入如下參數(shù)

{
   "configuredLevel": "DEBUG"
}

這個功能對于線上問題的排查非常有用偏窝。

同時收恢,你可以通過傳遞null值給configuredLevel來重置日志等級。

/info endpoint

info endpoint展示了應(yīng)用的基本信息囚枪。它通過META-INF/build-info.properties來獲得編譯信息派诬,通過git.properties來獲得Git信息。它同時可以展示任何其他信息链沼,只要這個環(huán)境property中含有infokey默赂。

你可以增加properties到application.yaml中,比如:

# INFO ENDPOINT CONFIGURATION
info:
  app:
    name: @project.name@
    description: @project.description@
    version: @project.version@
    encoding: @project.build.sourceEncoding@
    java:
      version: @java.version@

注意括勺,我使用了Spring Boot的Automatic property expansion 特征來擴展來自maven工程的properties缆八。

一旦你增加上面的properties,info endpoint將展示如下信息:

{
    "app": {
    "name": "actuator",
    "description": "Demo project for Spring Boot",
    "version": "0.0.1-SNAPSHOT",
    "encoding": "UTF-8",
    "java": {
        "version": "1.8.0_161"
        }
    }
}

使用Spring Security來保證Actuator Endpoints安全

Actuator endpoints是敏感的疾捍,必須保障進入是被授權(quán)的奈辰。如果Spring Security是包含在你的應(yīng)用中,那么endpoint是通過HTTP認(rèn)證被保護起來的乱豆。

如果沒有奖恰, 你可以增加以下以來到你的應(yīng)用中去:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

接下去讓我們看一下如何覆寫spring security配置,并且定義你自己的進入規(guī)則宛裕。

下面的例子展示了一個簡單的spring securiy配置瑟啃。它使用叫做EndPointRequest

ReqeustMatcher工廠模式來配置Actuator endpoints進入規(guī)則。

package com.example.actuator.config;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    /*
        This spring security configuration does the following

        1. Restrict access to the Shutdown endpoint to the ACTUATOR_ADMIN role.
        2. Allow access to all other actuator endpoints.
        3. Allow access to static resources.
        4. Allow access to the home page (/).
        5. All other requests need to be authenticated.
        5. Enable http basic authentication to make the configuration complete.
           You are free to use any other form of authentication.
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
                        .hasRole("ACTUATOR_ADMIN")
                    .requestMatchers(EndpointRequest.toAnyEndpoint())
                        .permitAll()
                    .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                        .permitAll()
                    .antMatchers("/")
                        .permitAll()
                    .antMatchers("/**")
                        .authenticated()
                .and()
                .httpBasic();
    }
}

為了能夠測試以上的配置揩尸,你可以在application.yaml中增加spring security用戶蛹屿。

# Spring Security Default user name and password
spring:
  security:
    user:
      name: actuator
      password: actuator
      roles: ACTUATOR_ADMIN

你可以在Github上看到完整的代碼。

下一部分:Spring Boot Metrics監(jiān)控之Prometheus&Grafana

更多學(xué)習(xí)資源

翻譯源

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末岩榆,一起剝皮案震驚了整個濱河市错负,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌勇边,老刑警劉巖犹撒,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異粒褒,居然都是意外死亡识颊,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門怀浆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來谊囚,“玉大人,你說我怎么就攤上這事执赡×ぃ” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵沙合,是天一觀的道長奠伪。 經(jīng)常有香客問我,道長首懈,這世上最難降的妖魔是什么绊率? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮究履,結(jié)果婚禮上滤否,老公的妹妹穿的比我還像新娘。我一直安慰自己最仑,他們只是感情好藐俺,可當(dāng)我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著泥彤,像睡著了一般欲芹。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上吟吝,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天菱父,我揣著相機與錄音,去河邊找鬼剑逃。 笑死浙宜,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的炕贵。 我是一名探鬼主播梆奈,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼称开!你這毒婦竟也來了亩钟?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤鳖轰,失蹤者是張志新(化名)和其女友劉穎清酥,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蕴侣,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡焰轻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了昆雀。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辱志。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡蝠筑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出揩懒,到底是詐尸還是另有隱情什乙,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布已球,位于F島的核電站臣镣,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏智亮。R本人自食惡果不足惜忆某,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望阔蛉。 院中可真熱鬧弃舒,春花似錦、人聲如沸馍忽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽遭笋。三九已至坝冕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間瓦呼,已是汗流浹背喂窟。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留央串,地道東北人磨澡。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像质和,于是被迫代替她去往敵國和親稳摄。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容