使用 Prometheus 观察 django-background-tasks 指标
Observing django-background-tasks metrics with Prometheus
我正在尝试在 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 的模型,但我发现它有点麻烦。
我最终创建了一个利用 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
我正在尝试在 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 的模型,但我发现它有点麻烦。
我最终创建了一个利用 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