Open Pyohwan opened 4 years ago
/actuator
prefix 를 사용하는 URL path 다.
health
는 /actuator/health
로 expose 한다
Actuator 는 기본적으로 Spring MVC, Spring WebFlux, and Jersey 를 지원한다.
때로는 커스텀 prefix 를 management 엔드포인트로 쓰는것이 유용하다.
actuator
를 사용중이라면, management.endpoints.web.base-path
로 management 엔드포인트 prefix 를 바꿀 수 있다.
management.endpoints.web.base-path=/manage
위에서는 /actuator/{id}
to /manage/{id}
(for example, /manage/info
). 로 바뀐다
management 포트가 다른 HTTP 포트로 구성되어 expose 안되었을 경우,
management.endpoints.web.base-path
는server.servlet.context-path
와 관련된다. 만약management.server.port
가 구성되면,management.endpoints.web.base-path
는management.server.servlet.context-path
와 관련된다.
엔드포인트를 다른 path 로 맵 하고 싶을때는 management.endpoints.web.path-mapping
를 써라
다음은 /actuator/health
to /healthcheck
로 리맵하는 예제다
management.endpoints.web.base-path=/
management.endpoints.web.path-mapping.health=healthcheck
management.server.port
로 바꿀수 있다
management.server.port=8081
Cloud Foundry 에서는 8080 port 에서 HTTP 와 TCP 라우팅을 요청을 받습니다.
management.server.ssl.*
를 이용해 SSL 로 구성할 수 있다.server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:store.jks
server.ssl.key-password=secret
management.server.port=8080
management.server.ssl.enabled=false
server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:main.jks
server.ssl.key-password=secret
management.server.port=8080
management.server.ssl.enabled=true
management.server.ssl.key-store=classpath:management.jks
management.server.ssl.key-password=secret
management.server.address
로 management 엔드포인트가 사용 가능한 adress 를 커스텀 가능localhost
만 listen 하고 싶을때 유용하다.
메인 서버 포트와 달라야만 다른 address 에서 listen 가능하다
management.server.port=8081
management.server.address=127.0.0.1
management.server.port=-1
management.endpoints.web.exposure.exclude
를 써도 된다
management.endpoints.web.exposure.exclude=*
id
엔드포인트로 생성 된다.
health
엔드포인트는 org.springframework.boot:type=Endpoint,name=Health
로 expose 된다ApplicationContext
가 있다면 충돌날 수 있다.
spring.jmx.unique-names=true
management.endpoints.jmx.domain=com.example.myapp
management.endpoints.jmx.exposure.exclude=*
org.jolokia:jolokia-core
를 추가해라
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
management.endpoints.web.exposure.include
에 jolokia or * 을 넣으면, Jolokia 엔드포인트가 expose 된다
/actuator/jolokia
로 접근 가능management.endpoint.jolokia.config.
로 설정 가능하다
management.endpoint.jolokia.config.debug=true
management.endpoint.jolokia.enabled=false
{
"configuredLevel": "DEBUG"
}
로거 레벨을 "reset" 하기 위해(기본 구성을 사용하려고),
configuredLevel
을null
로 할 수 있다.
MeterRegistry
를 자동구성하고, classpath 에서 알맞은 registry 도 추가 함
micrometer-registry-{system}
가 있으면 됨management.metrics.export.datadog.enabled=false
Metrics
에 추가한다.
management.metrics.use-global-registry=false
MeterRegistryCustomizer
빈을 등록가능하다.
@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags("region", "us-east-1");
}
@Bean
MeterRegistryCustomizer<GraphiteMeterRegistry> graphiteMetricsNamingConvention() {
return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION);
}
컴포넌트의 MeterRegistry
에 주입 가능하고, metrics 을 등록할 수 있다
@Component
public class SampleBean {
private final Counter counter;
public SampleBean(MeterRegistry registry) {
this.counter = registry.counter("received.messages");
}
public void handleMessage(String message) {
this.counter.increment();
// handle message implementation
}
}
* 스프링부트는 설정과 애너테이션으로 bulit-in instrumentation (i.e. MeterBinder implementations) 을 구성한다.
## 6.2. Supported monitoring systems
### 6.2.1. AppOptics
* 기본적으로 AppOptics registry 는 `api.appoptics.com/v1/measurements` 로 메트릭을 주기적으로 push 한다.
* API token 은 필수다
management.metrics.export.appoptics.api-token=YOUR_TOKEN
### 6.2.5. Elastic
* 기본적으로 메트릭은 로컬머신에서 실행중인 `Elastic` 으로 export 된다.
* 사용할 Elastic 서버는 다음과 같이 사용한다.
management.metrics.export.elastic.host=https://elastic.example.com:8086
### 6.2.13. Prometheus
* Prometheus 는 개별 앱 인스턴스의 메트릭을 poll 할것으로 기대한다.
* Spring Boot 는 `/actuator/prometheus` 액츄에이터 엔드포인트를 제공하고, Prometheus 가 scrape(긁어) 해갈수 있다
> 엔드포인트는 기본적으로 사용할 수 없기 때문에, expose 시켜야 한다
* `prometheus.yml` 에 `scrape_config` 을 추가한 예제이다.
scrape_configs:
* ephemeral(수명이 짧은) 혹은 배치 잡에서 Prometheus Pushgateway 를 통해 Prometheus 로 메트릭을 expose 할 수 있다.
* Prometheus Pushgateway 사용하려면 디펜던시 추가 필요
* classpath에 위 디펜던시가 있다면 `PrometheusPushGatewayManager` 를 자동구성 함
management.metrics.export.prometheus.pushgateway
로도 설정 가능management.metrics.export.simple.enabled=false
자동구성으로 Spring MVC 가 처리하는 요청을 계측가능하다
management.metrics.web.server.request.autotime.enabled
가 true
이면 모든 요청을 계측. false
이면 @Timed
붙은 것만 계측
@RestController
@Timed
public class MyController {
@GetMapping("/api/people")
@Timed(extraTags = { "region", "us-east-1" })
@Timed(value = "all.people", longTask = true)
public List
}
* 컨트롤러로 들어오는 모든 요청의 timings 을 활성화
* 개별적인 엔드포인트 활성화.
* long task 일 경우 `longTask = true` 붙힘
* Long task timers 는 별도의 메트릭 이름이 필요하고, short 태스크 타이머도 쌓일 수 있음
* 기본적으로 메트릭 이름은 `http.server.requests` 로 생성 됨
* `management.metrics.web.server.request.metric-name` 로 커스텀 가능
* 기본적인 Spring MVC-related 메트릭 정보는 다음의 표처럼 tag 됨
Tag | Description
-- | --
exception | Simple class name of any exception that was thrown while handling the request.
method | Request’s method (for example, GET or POST)
outcome | Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR
status | Response’s HTTP status code (for example, 200 or 500)
uri | Request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})
* `WebMvcTagsProvider` 구현해서 커스터마이징 가능
### 6.3.2. Spring WebFlux Metrics
* 자동구성으로 WebFlux 컨트롤러나 functional 핸들러를 통한 모든 요청을 계측 가능하다
* 기본적으로 메트릭 이름은 `http.server.requests` 로 생성 됨
* `management.metrics.web.server.request.metric-name` 로 커스텀 가능
* 기본적인 WebFlux-related 메트릭 정보는 다음의 표처럼 tag 됨
Tag | Description
-- | --
exception | Simple class name of any exception that was thrown while handling the request.
method | Request’s method (for example, GET or POST)
outcome | Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR
status | Response’s HTTP status code (for example, 200 or 500)
uri | Request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})
* `WebFluxTagsProvider` 구현해서 커스터마이징 가능
### 6.3.3. Jersey Server Metrics
* 생략
### 6.3.4. HTTP Client Metrics
* Spring Boot Actuator 는 `RestTemplate` 와 `WebClient` 의 계측도 관리한다
* 이를 위해 자동구성된 빌더를 inject 하고 객체를 만들어야 한다
* RestTemplateBuilder for RestTemplate
* WebClient.Builder for WebClient
* `MetricsRestTemplateCustomizer` 나 `MetricsWebClientCustomizer` 로 수동으로 커스터마이징 가능
* 기본적으로 메트릭 이름은 `http.server.requests` 로 생성 됨
* `management.metrics.web.server.request.metric-name` 로 커스텀 가능
* 기본적인 메트릭 정보는 다음의 표처럼 tag 됨
Tag | Description
-- | --
clientName | Host portion of the URI
method | Request’s method (for example, GET or POST)
outcome | Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR, UNKNOWN otherwise
status | Response’s HTTP status code if available (for example, 200 or 500), or IO_ERROR in case of I/O issues, CLIENT_ERROR otherwise
uri | Request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})
* 태그 커스터마이징을 하기 위해선 `RestTemplateExchangeTagsProvider` 나 `WebClientExchangeTagsProvider` 를 구현면 됨
* 또한 편리한 static functions 가 `RestTemplateExchangeTags` 와 `WebClientExchangeTags` 에 있음
### 6.3.5. Cache Metrics
* 자동구성으로 startup 시 `cache` prefix 붙은 사용가능한 모든 `Cache` 를 계측 가능하다
* 캐시 계측은 기본 메트릭 세트로 표준화 되었음
* 추가적인 캐시 라이브리리들
* Caffeine
* EhCache 2
* Hazelcast
* Any compliant JCache (JSR-107) implementation
* 메트릭은 태그는 `CacheManager` 에 있는 cacheName 으로 된다
> 오로지 startup 시에 이용가능한 캐시만 bound 된다. on-the-fly 혹은 startup 이후 프로그래밍적으로 만들려면, 명시적으로 등록해라. `CacheMetricsRegistrar` bean 은 프로세스를 보다 쉽게 해준다
### 6.3.6. DataSource Metrics
* 자동구성으로 시 `jdbc.connections ` prefix 붙은 사용가능한 모든 `DataSource ` 를 계측 가능하다
* Data source 계측으로 currently active, idle, maximum allowed, and minimum allowed connections in the pool 을 알 수 있다
* 메트릭은 `DataSource` 의 bean 이름 기반으로 태그 된다
> 기본적으로 스프링부트가 제공하는 모든 data sources 의 메타데이터를 제공한다. 별도로 추가하려면 `DataSourcePoolMetadataProvider` bean 을 만들어라. `DataSourcePoolMetadataProvidersConfiguration` 에 예제 있음
* Hikari-specific metrics 은 `hikaricp` prefix 로 expose 된다. 각 메트릭은 풀 이름으로 태그 된다. (`spring.datasource.name` 로 조절 가능)
### 6.3.7. Hibernate Metrics
* 자동구성으로 이용가능한 Hibernate `EntityManagerFactory` 객체를 `hibernate` 란 이름으로 계측 된다
* 메트릭은 `EntityManagerFactory` bean 이름으로 태그된다
* 표준 JPA 설정을 enable 해야 한다. `hibernate.generate_statistics`
* 다음 예제처럼 자동구성된 `EntityManagerFactory` 를 활성화 한다
spring.jpa.properties.hibernate.generate_statistics=true
### 6.3.8. RabbitMQ Metrics
* 자동구성으로 이용가능한 모든 RabbitMQ 커넥션 팩토리를 `rabbitmq` 란 이름으로 계측가능하다
## 6.4. Registering custom metrics
* 커스텀 메트릭을 등록하려면 `MeterRegistry` 를 컨포넌트로 주입하라
```java
class Dictionary {
private final List<String> words = new CopyOnWriteArrayList<>();
Dictionary(MeterRegistry registry) {
registry.gaugeCollectionSize("dictionary.size", Tags.empty(), this.words);
}
// …
}
MeterBinder
구현체를 캡슐화 한다
MeterBinder
beans 은 자동으로 Spring-managed MeterRegistry
에 바인드 된다Meter
객체를 커스텀해야 한다면, io.micrometer.core.instrument.config.MeterFilter
객체를 이용해라
MeterFilter
beans 은 자동으로 MeterRegistry.Config
마이크로미터에 적용된다com.example
로 시작하는 모든 meter IDs 의 mytag.region
태그 이름을 mytag.area
로 바꾸려면 다음과 같이 해라
@Bean
public MeterFilter renameRegionTagMeterFilter() {
return MeterFilter.renameTag("com.example", "mytag.region", "mytag.area");
}
management.metrics.tags.region=us-east-1
management.metrics.tags.stack=prod
region
과 stack
태그를 us-east-1
와 prod
에 추가한다.
Graphite 를 사용할때에는 common 태그의 순서가 중요하다. 이 방법으로는 common 태그의 순서를 보장하지 못하므로, Graphite 사용자는
MeterFilter
를 정의해서 쓰는게 낫다
MeterFilter
beans 이외에도 properties 를 사용해서 per-meter 제한된 커스텀이 가능하다example.remote
로 시작하는 ID 를 disable 한다
management.metrics.enable.example.remote=false
Property | Description |
---|---|
management.metrics.enable | Whether to deny meters from emitting any metrics. |
management.metrics.distribution.percentiles-histogram | Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations. |
management.metrics.distribution.minimum-expected-value, management.metrics.distribution.maximum-expected-value | Publish less histogram buckets by clamping the range of expected values. |
management.metrics.distribution.percentiles | Publish percentile values computed in your application |
management.metrics.distribution.sla | Publish a cumulative histogram with buckets defined by your SLAs. |
percentiles-histogram
percentiles
sla
개념에 대한 자세한 것은 "Histograms and percentiles" section 참고metrics
엔드포엔트를 제공한다
/actuator/metrics
에 가보면 이용가능한 meter 이름 목록이 있다
/actuator/metrics/jvm.memory.max
여기에서 사용하는 이름은 코드와 일치해야 한다. Prometheus 에서는
jvm.memory.max
는jvm_memory_max
로 나타내므로, 엔드포인트에서 meter 를 검사할때jvm.memory.max
를 사용 해야 한다
tag=KEY:VALUE
쿼리 파라미터를 URL 끝에 추가할 수 있다.
/actuator/metrics/jvm.memory.max?tag=area:nonheap
reported 된 측정치는 미터 이름, 태그와 일치하는 모든 통계의 합(sum) 이다. 따라서 위 응답의 "Value" 는 "Code Cache", "Compressed Class Space", and "Metaspace" areas of the heap 의 합이다. 메타스페이스의 최대 크기를 알고 싶다면
tag=id:Metaspace
를 추가해라. i.e./actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace
AuditEventRepository
로 구성하여 활성화 가능InMemoryAuditEventRepository
제공한다
InMemoryAuditEventRepository
는 기능이 제한적이라 개발 환경에서만 써라AuditEventRepository
를 직접 만들어라AbstractAuthenticationAuditListener
AbstractAuthorizationAuditListener
구현해라AuditEventRepository
빈 직접 주입AuditApplicationEvent
ApplicationEventPublisher
구현 (by implementing ApplicationEventPublisherAware)InMemoryHttpTraceRepository
제공하는데 마지막 100개의 요청-응답을 추적가능하다
InMemoryHttpTraceRepository
는 개발환경에서만 쓰고, 프로덕션에서는 Zipkin, Spring Cloud Sleuth 추천한다HttpTraceRepository
를 직접 만들어라httptrace
엔드포인트에서 HttpTraceRepository
에 저장된 request-response exchanges 정보를 얻을 수 있다
management.trace.http.include
를 이용해라HttpExchangeTracer
를 구현해라ApplicationPidFileWriter
는 애플리케이션 PID 를 포함하는 파일 만듦 (기본적으로 application.pid
란 파일)WebServerPortFileWriter
실행중인 웹서버 포트를 포함하는 파일을 만듦 (기본적으로 application.port
란 파일)
META-INF/spring.factories
파일에서 리스너 활성화 가능
org.springframework.context.ApplicationListener=\
org.springframework.boot.context.ApplicationPidFileWriter,\
org.springframework.boot.web.context.WebServerPortFileWriter
pringApplication.addListeners(…)
로 Writer
객체를 전달해서 리스너 주입 가능
https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/html/production-ready-features.html#production-ready-enabling
1. Enabling Production-ready Features
spring-boot-actuator
모듈이 모든 운영 환경 기능을 제공한다가장 쉬운 방법은 spring-boot-starter-actuator ‘Starter’ 를 추가해라
Definition of Actuator
액츄에이터는 물건을 움직이거나 제어를 위한 기계 장치(제조 용어)
액츄에이터는 작은 변화로 많은 움직임(motion)을 생성할 수 있다.
2. Endpoints
액츄에이터 엔드포인트를 사용하면 애플리케이션을 모니터링하고 상호작용 가능하다
Spring Boot 에는 built-in 엔드포인트가 여러개 포함되어 있고, 사용자가 직접 추가도 가능하다
health
엔드포인트는 애플리케이션의 기본 health 정보를 제공한다개별 엔드포인트는 비활성화 가능하다
원격 접근 할려면 JMX or HTTP 로 노출(expose) 해야 한다
/actuator
과 함께 엔드포인트가 URL 에 매핑된다/actuator/health
사용 가능한 technology-agnostic endpoints
2.1. Enabling Endpoints
shutdown
을 제외한 모든 엔드포인트는 활성화management.endpoint.<id>.enabled
로 컨트롤 가능shutdown
엔드포인트 활성화 하기management.endpoints.enabled-by-default
를false
로 해라.enabled
해라info
엔드포인트를 enabled 하고 다른 모든 엔드포인트들을 disables 한다.2.2 Exposing Endpoints
include
는 expose 를 원하는 엔드포인트의 IDs 목록이다.exclude
는 반대로 expose 를 원하지 않는 엔드포인트의 IDs 목록이다.exclude
가include
보다 우선순위가 높다health
와info
엔드포인트만 expose 하고 싶다면?*
로 모든 엔드포인트 선택 가능env
와beans
을 제외한 모든 것을 HTTP 를 통해 expose 하고 싶다면?2.3. Securing HTTP Endpoints
RequestMatcher
를 제공한다일반적인 Spring Security 구성은 다음과 유사하다
EndpointRequest.toAnyEndpoint()
는 모든 엔드포인트를 말하고,ENDPOINT_ADMIN
role 을 가졌는지 검사추가적으로 미인증 접근에 대해서 엔드포인트 접근을 허용하기 위해선
}
management.endpoint.beans.cache.time-to-live=10s
management.endpoints.web.cors.allowed-origins=https://example.com management.endpoints.web.cors.allowed-methods=GET,POST
Input type conversion
2.7.2. Custom Web Endpoints
Web Endpoint Request Predicates
Path
/actuator
이다sessions
인 경우, predicate 의 path 는/actuator/sessions
이다@Selector
와 파라미터 조합으로 커스터마이징 가능@Selector(Match=ALL_REMAINING)
String[]
타입으로 넣을 수 있음HTTP method
Consumes
application/vnd.spring-boot.actuator.v2+json, application/json
이다.Produces
application/octet-stream
이다application/vnd.spring-boot.actuator.v2+json, application/json
이다Web Endpoint Response Status
Web Endpoint Range Requests
Web Endpoint Security
2.7.3. Servlet endpoints
2.7.4. Controller endpoints
2.8. Health Information
health
엔드포인트로 expose 된다management.endpoint.health.show-details
와management.endpoint.health.show-components
로 구성 가능never
management.endpoint.health.roles
로 구성 가능HealthContributorRegistry
에서 수집 한다. (기본적으로 HealthContributor 객체)HealthContributor
는HealthIndicator
orCompositeHealthContributor
로 될 수 있다.HealthIndicator
는Status
를 포함하는 실제 health 정보를 제공CompositeHealthContributor
는 다른HealthContributors
와 혼합을 제공StatusAggregator
(HealthIndicator 에서 status 를 정렬한) 에서 유래한다.HealthIndicator
응답이 없다면 UNKNOWN status 가 사용된다2.8.1. Auto-configured HealthIndicators
HealthIndicators
2.8.2. Writing Custom HealthIndicators
HealthIndicator
인터페이스 구현해서 커스터마이징 해라health()
메소드와Health
응답 반환을 제공해라Health
응답은 status 를 포함해야 하고, 선택적으로 세부 정보도 넣을 수 있다@Component public class MyHealthIndicator implements HealthIndicator {
}
management.endpoint.health.status.order=fatal,down,out-of-service,unknown,up
management.endpoint.health.status.http-mapping.fatal=503
@Component public class MyReactiveHealthIndicator implements ReactiveHealthIndicator {
}
management.endpoint.health.group.custom.include=db
management.endpoint.health.group.custom.show-details=when-authorized management.endpoint.health.group.custom.roles=admin management.endpoint.health.group.custom.status.order=fatal,up management.endpoint.health.group.custom.status.http-mapping.fatal=500
info.app.encoding=UTF-8 info.app.java.source=1.8 info.app.java.target=1.8
info.app.encoding=@project.build.sourceEncoding@ info.app.java.source=@java.version@ info.app.java.target=@java.version@
management.info.git.mode=full
import java.util.Collections;
import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component;
@Component public class ExampleInfoContributor implements InfoContributor {
}
{ "example": { "key" : "value" } }