prometheus自定义监控指标——实战

本文通过实例讲解如何使用shell和Python自定义Prometheus监控指标,包括监控容器启动时间和使用Python客户端发送数据。强调了数据类型的重要性,如counter和gauge,并提醒注意数据格式以避免数据丢失。
摘要由CSDN通过智能技术生成

上一节介绍了pushgateway的作用、优劣以及部署使用,本机通过几个实例来重温一下自定义监控指标是如何使用的。


一、监控容器启动时间(shell)

  使用prometheus已经两个月了,但从未找到容器运行时间的指标(有一个类似的指标是容器创建时间)。学会自定义监控指标后,第一个实例就应该来搞定它。

  前提条件是,部署好pushagateway!

  在被监控机器上(linux),创建以下脚本

#!/bin/bash
  
allname=`docker ps --format "{
   {.Names}}"`              #获取所有运行的容器名称

function dockerruntime(){
    t=`docker inspect -f '{
   {.State.StartedAt}}' $1`          #获取各个容器的启动时间
    t1=`date +%s -d "$t"`                                    #将时间转成时间戳
    t2=`date +%s`                                            #获取当前时间的时间戳
    let tt=t2-t1                                             #计算运行时间
    echo $tt
}

sudo rm -f a
echo &
Spring Boot是一个用于创建独立的、基于生产级别的Java应用程序的框架。而Prometheus是一个开源的监控和警报系统,用于记录和查询应用程序的时间序列数据。在Spring Boot中集成Prometheus可以方便地监控和度量应用程序的性能指标。 要在Spring Boot中集成Prometheus自定义Prometheus指标,可以按照以下步骤进行操作: 1. 添加依赖:在Spring Boot项目的pom.xml文件中添加Prometheus相关的依赖。例如: ```xml <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> ``` 2. 配置Prometheus:在Spring Boot项目的配置文件(如application.properties或application.yml)中添加Prometheus相关的配置。例如: ```yaml management: endpoints: web: exposure: include: prometheus ``` 这样配置后,Spring Boot会自动将Prometheus监控端点暴露出来。 3. 自定义指标:在代码中使用Micrometer库来定义和记录自定义指标。Micrometer是一个度量库,可以与Prometheus集成。例如,可以使用`Counter`来记录计数器指标,使用`Gauge`来记录度量指标等。以下是一个示例: ```java import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CustomMetrics { private final Counter customCounter; @Autowired public CustomMetrics(MeterRegistry meterRegistry) { customCounter = meterRegistry.counter("custom_counter"); } public void incrementCustomCounter() { customCounter.increment(); } } ``` 在上述示例中,我们定义了一个名为`custom_counter`的计数器指标,并通过`MeterRegistry`将其注册到Micrometer中。 4. 访问指标启动Spring Boot应用程序后,可以通过访问`/actuator/prometheus`端点来获取Prometheus格式的指标数据。例如,可以使用浏览器或curl命令访问`http://localhost:8080/actuator/prometheus`来获取指标数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值