- 本文springboot版本:
1.5.4.RELEASE
- 如果使用springboot2.x,請參考springboot2.x-actuator
spring-boot-actuator模塊提供了一個監控和管理生產環境的模塊,可以使用http、jmx、ssh、telnet等來管理和監控應用。審計(Auditing)、 健康(health)、數據采集(metrics gathering)會自動加入到應用里面。
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
可以在你的application.yml
配置文件配置:
##運行狀態 actuator監控
endpoints:
enabled: true
info:
sensitive: false
health:
sensitive: false
management:
##服務路徑
context-path: /
##服務端口
port: 8081
如果你使用application.properties
,可以做類似的配置:
endpoints.enabled=true
endpoints.info.sensitive=false
endpoints.health.sensitive=false
management.context-path=/
management.port=8081
啟動后可以看到以下日志:
2017-03-15 15:50:58.775 INFO 9544 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Detected ResponseBodyAdvice bean in org.springframework.boot.actuate.autoconfigure.EndpointWebMvcHypermediaManagementContextConfiguration$ActuatorEndpointLinksAdvice
2017-03-15 15:50:58.956 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.957 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.958 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2017-03-15 15:50:58.958 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.959 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/health || /health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)
2017-03-15 15:50:58.960 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.960 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.961 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.963 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/heapdump || /heapdump.json],methods=[GET],produces=[application/octet-stream]}" onto public void org.springframework.boot.actuate.endpoint.mvc.HeapdumpMvcEndpoint.invoke(boolean,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException,javax.servlet.ServletException
2017-03-15 15:50:58.964 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/actuator || /actuator.json],produces=[application/json]}" onto public org.springframework.hateoas.ResourceSupport org.springframework.boot.actuate.endpoint.mvc.HalJsonMvcEndpoint.links()
2017-03-15 15:50:58.965 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/info || /info.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.973 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2017-03-15 15:50:58.973 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env || /env.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-03-15 15:50:58.974 INFO 9544 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
接口
接口 | 描述 | 敏感 |
---|---|---|
actuator | 列出所有可用接口 | true |
autoconfig | 顯示一個auto-configuration的報告,該報告展示所有auto-configuration候選者及它們被應用或未被應用的原因 | true |
beans | 顯示一個應用中所有Spring Beans的完整列表 | true |
configprops | 顯示一個所有@ConfigurationProperties的整理列表 | true |
dump | 顯示當前應用線程狀態信息 | true |
env | 顯示Spring的ConfigurableEnvironment屬性 | true |
health | 展示應用的健康信息(當使用一個未認證連接訪問時顯示一個簡單的’status’,使用認證連接訪問則顯示全部信息詳情) | false |
info | 顯示應用信息 | false |
metrics | 展示當前應用的’指標’信息 | true |
mappings | 顯示一個所有@RequestMapping路徑的整理列表 | true |
shutdown | 允許應用以優雅的方式關閉(默認情況下不啟用) | true |
trace | 顯示trace信息(默認情況下是最后100個HTTP請求) | true |
loggers | 提供顯示和修改應用程序中loggers配置的功能 | true |
測試幾個接口
/health
訪問http://127.0.0.1:8081/health 可以看到
{
"status":"UP",
"hello":{
"status":"UP"
},
"diskSpace":{
"status":"UP",
"total":116333809664,
"free":86622515200,
"threshold":10485760
},
"db":{
"status":"UP",
"database":"Oracle",
"hello":"Hello"
}
}
自動配置的HealthIndicators
下面的HealthIndicators會被Spring Boot自動配置(在合適的時候):
名字 | 描述 |
---|---|
CassandraHealthIndicator | 檢查Cassandra database是否正常 |
DiskSpaceHealthIndicator | 低磁盤空間檢測 |
DataSourceHealthIndicator | 檢查數據庫連接是否正常 |
ElasticsearchHealthIndicator | 檢查Elasticsearch cluster是否正常 |
JmsHealthIndicator | 檢查JMS broker是否正常 |
MailHealthIndicator | 檢查mail server是否正常 |
MongoHealthIndicator | 檢查Mongo database是否正常 |
RabbitHealthIndicator | 檢查Rabbit server是否正常 |
RedisHealthIndicator | 檢查Redis server是否正常 |
SolrHealthIndicator | 檢查Solr server是否正常 |
編寫自定義HealthIndicators
想提供自定義健康信息,你可以注冊實現了HealthIndicator接口的Spring beans。你需要提供一個health()方法的實現,并返回一個Health響應。Health響應需要包含一個status和可選的用于展示的詳情。比如上面/health
接口中的hello就是再下面定義的
@Component
public class HelloHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode) .build();
}
return Health.up().build();
}
int check(){
return 0;
}
}
/metrics
{
"counter.status.200.root": 20,
"counter.status.200.metrics": 3,
"counter.status.200.star-star": 5,
"counter.status.401.root": 4,
"gauge.response.star-star": 6,
"gauge.response.root": 2,
"gauge.response.metrics": 3,
"classes": 5808,
"classes.loaded": 5808,
"classes.unloaded": 0,
"heap": 3728384,
"heap.committed": 986624,
"heap.init": 262144,
"heap.used": 52765,
"nonheap": 0,
"nonheap.committed": 77568,
"nonheap.init": 2496,
"nonheap.used": 75826,
"mem": 986624,
"mem.free": 933858,
"processors": 8,
"threads": 15,
"threads.daemon": 11,
"threads.peak": 15,
"threads.totalStarted": 42,
"uptime": 494836,
"instance.uptime": 489782,
"datasource.primary.active": 5,
"datasource.primary.usage": 0.25
}
此處我們可以看到基本的 memory , heap , class loading , processor 和 thread pool 信息,連同一些HTTP指標,還可以使用 / /{name:.} 訪問單個屬性。在該實例中, root ('/'), /metrics URLs分別返回20次,3次 HTTP 200 響應。同時可以看到 root URL返回了4次 HTTP 401 (unauthorized)響應。雙asterix(star-star)來自于被Spring MVC /* 匹配到的一個請求(通常為一個靜態資源)。
gauge 級別展示了一個請求的最后響應時間。所以, root 的最后請求被響應耗時2毫秒, /metrics 耗時3毫秒。
Spring Boot提供以下系統指標:
系統內存總量(mem),單位:Kb
空閑內存數量(mem.free),單位:Kb
處理器數量(processors)
系統正常運行時間(uptime),單位:毫秒
應用上下文(就是一個應用實例)正常運行時間(instance.uptime),單位:毫秒
系統平均負載(systemload.average)
堆信息(heap,heap.committed,heap.init,heap.used),單位:Kb
線程信息(threads,thread.peak,thead.daemon)
類加載信息(classes,classes.loaded,classes.unloaded)
垃圾收集信息(gc.xxx.count, gc.xxx.time)
還會為你應用中定義的支持的DataSource提供 以下指標:
最大連接數(datasource.xxx.max)
最小連接數(datasource.xxx.min)
活動連接數(datasource.xxx.active)
連接池的使用情況( .xxx.usage)
所有的數據源指標共用 datasoure. 前綴。該前綴對每個數據源都非常合適:
如果是主數據源(唯一可用的數據源或存在的數據源中被@Primary標記的)前綴為datasource.primary
如果數據源bean名稱以dataSource結尾,那前綴就是bean的名稱去掉dataSource的部分(例如,batchDataSource的前
綴是datasource.batch)
其他情況使用bean的名稱作為前綴
記錄自己的指標
想要記錄你自己的指標,只需將CounterService
或GaugeService
注入到你的bean中。CounterService
提供increment
:將指定的計數器增加1。,decrement
:將指定的計數器減1。和reset
:復位指定的計數器。 方法;GaugeService
提供一個submit
方法。
@Service
public class UserService {
@Autowired
UserMapper mapper;
@Autowired
CounterService counterService;
@Autowired
GaugeService gaugeService;
public Map<Object, Object> findById(String id) {
this.counterService.increment("services.system.userService.findById.invoked");
gaugeService.submit("a", 1.0);
return mapper.findById(id);
}
}
/trace
[
{
"timestamp":1489568887768,
"info":{
"method":"GET",
"path":"/",
"headers":{
"request":{
"host":"127.0.0.1:8080",
"connection":"keep-alive",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"zh-CN,zh;q=0.8"
},
"response":{
"X-Application-Context":"youyu:localdev:8080",
"status":"404"
}
}
}
},
{
"timestamp":1489568886967,
"info":{
"method":"GET",
"path":"/",
"headers":{
"request":{
"host":"127.0.0.1:8080",
"connection":"keep-alive",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"zh-CN,zh;q=0.8"
},
"response":{
"X-Application-Context":"youyu:localdev:8080",
"status":"404"
}
}
}
}
]
/loggers
訪問http://127.0.0.1:8081/loggers
返回:
{
"levels":[
"OFF",
"ERROR",
"WARN",
"INFO",
"DEBUG",
"TRACE"
],
"loggers":{
"ROOT":{
"configuredLevel":"INFO",
"effectiveLevel":"INFO"
},
"com":{
"configuredLevel":null,
"effectiveLevel":"INFO"
},
"com.caiyi":{
"configuredLevel":null,
"effectiveLevel":"INFO"
}
...
}
}
可以通過post
請求http://127.0.0.1:8081/loggers/{elephant}
修改不同包下的日志級別。
舉個栗子:訪問
http:127.0.0.1:8081/manage/loggers/com.caiyi
請求body中傳參數:
{
"configuredLevel": "debug"
}
就能修改com.caiyi
下面的日志級別為debug
,用get
請求一下http://127.0.0.1:8081/manage/loggers/com.caiyi
可看到修改成功了:
{
"configuredLevel": "DEBUG",
"effectiveLevel": "DEBUG"
}