【问题标题】:Observing django-background-tasks metrics with Prometheus使用 Prometheus 观察 django-background-tasks 指标
【发布时间】:2021-01-13 03:25:12
【问题描述】:

我正在尝试在 Django 中为 django-background-tasks 调用的函数收集特定于应用程序的 Prometheus 指标。

在我的应用程序models.py 文件中,我首先添加了一个自定义指标:

my_task_metric = Summary("my_task_metric ", "My task metric")

然后,我将其添加到我的函数中以捕获此函数上次成功运行的时间戳:


@background()
def my_function():

    # my function code here

    # collecting the metric
    my_task_metric.observe((datetime.now().replace(tzinfo=timezone.utc) - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds())

当我启动 Django 时,会在 /metrics 中创建和访问指标。但是,在运行此函数后,sum 的值为 0,就好像未观察到度量一样。我错过了什么吗?

或者有没有更好的方法来使用 Prometheus 监控 django-background-tasks?我尝试过使用 django-background-tasks 的模型,但我发现它有点麻烦。

【问题讨论】:

    标签: python django prometheus


    【解决方案1】:

    我最终创建了一个利用 Prometheus Pushgateway 功能的装饰器

    def push_metric_to_prometheus(function):
    
        registry = CollectorRegistry()
    
        Gauge(f'{function.__name__}_last_successful_run', f'Last time {function.__name__} successfully finished',
              registry=registry).set_to_current_time()
    
        push_to_gateway('bolero.club:9091', job='batchA', registry=registry)
    
        return function
    

    然后是我的函数(装饰器的顺序很重要)

    @background()
    @push_metric_to_prometheus
    def my_function():
    
        # my function code here
    

    【讨论】:

      猜你喜欢
      • 2015-08-29
      • 2022-08-10
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 2020-01-10
      • 2017-05-03
      • 2018-01-07
      • 2021-03-23
      相关资源
      最近更新 更多