【问题标题】:Logging Spring Boot Actuator health status in the application log file在应用程序日志文件中记录 Spring Boot Actuator 健康状态
【发布时间】:2019-10-08 16:44:32
【问题描述】:
目前我们正在使用 Spring boot actuator vr 1.5.10,我们可以通过 /health 端点成功访问我们的健康页面。但是在访问我们的健康端点时,我们还需要在应用程序的日志文件中记录该健康状态,以便稍后我们可以根据状态创建 Kibana 观察者警报。
我看到我们可以使用“@EndpointWebExtension”扩展健康端点,并按照here 的建议在此处记录状态。但似乎 vr 1.5.10 不支持这一点。
任何方向都将不胜感激!
【问题讨论】:
标签:
java
spring-boot
logging
spring-boot-actuator
【解决方案1】:
您可以编写自己的 HealthAggregator 并在其中设置 Default Spring Aggregator 并使用它。
public class OwnHealthAggregator implements HealthAggregator {
private final HealthAggregator defaultHealth;
public OwnHealthAggregator(HealthAggregator defaultHealth) {
this.defaultHealth = defaultHealth;
}
@Override
public Health aggregate(Map<String, Health> healths) {
Health result = this.defaultHealth.aggregate(healths);
// LOG Result here
return result;
}
}
定义一个bean并使用默认的:
@Bean
public HealthAggregator health() {
return new OwnHealthAggregator(new OrderedHealthAggregator());
}
当你在这个版本中使用执行器时,你应该小心,因为默认情况下会启用许多端点(如 /beans、/env、/dump)。
【解决方案2】:
Spring 将注入实现特定接口的所有组件的列表。
例如:
private List<HealthIndicator> healthIndicatorList
将包含实现HealthIndicator 类的每个类。
您可以在自己的组件中实现HealthIndicator 类,然后
然后在 healthIndicatorList 的每个成员上调用health() 方法并记录结果。
当然,
不要递归调用日志健康指示器的health() 方法。
这是一些代码:
@Component
public class LoggingHealthIndicator implements HealthIndicator
{
@Autowired
private List<HealthIndicator> healthIndicatorList
@Override
public Health health()
{
for (final HealthIndicator current : healthIndicatorList)
{
if (current != this)
{
// assumes SLF4j
logger.log("blam message; {}", current.health());
}
}
return Health.up().build();
}
}
该代码可能不起作用,因为您的班级想要所有
HealthIndicor 实现并且本身就是一个 HealthIndicator。
您可能需要添加 @PostConstruct 方法并自己检索 HealthIndictor 组件列表。