跳转至

添加 Logfire 指标

Pydantic Logfire 可用于从您的应用程序收集指标并将其发送到指标后端。

让我们看看如何在应用程序中创建和使用指标。

import logfire

# 创建计数器指标
messages_sent = logfire.metric_counter('messages_sent')

# 增加计数器
def send_message():
    messages_sent.add(1)

指标类型

指标是记录数字值的好方法,在这些值中,您希望看到数据的聚合(例如,随着时间的推移),而不是单个值。

计数器

当您想要测量应用程序中特定事件或状态的频率或发生次数时,Counter 指标特别有用。

您可以使用此指标来计算以下事项:

  • 捕获的异常数。

  • 收到的请求数。

  • 已处理的项目数。

要创建计数器指标,请使用 logfire.metric_counter 功能:

import logfire

counter = logfire.metric_counter(
    'exceptions',
    unit='1',  # (1)!
    description='Number of exceptions caught'
)

try:
    raise Exception('oops')
except Exception:
    counter.add(1)
  1. unit 参数是可选的,但最好指定它。它应该是一个字符串,表示计数器的单位。如果度量是_无单位_的,则可以使用“1”。

可以在 OpenTelemetry 文档中阅读有关计数器指标的更多信息。

直方图

当您想要测量一组值的分布时,直方图指标特别有用。

您可以使用此指标来衡量以下内容:

  • 请求的持续时间。

  • 文件大小。

  • 列表中的项目数。

要创建直方图指标,请使用 logfire.metric_histogram功能:

import logfire

histogram = logfire.metric_histogram(
    'request_duration',
    unit='ms',  # (1)!
    description='Duration of requests'
)

for duration in [10, 20, 30, 40, 50]:
    histogram.record(duration)
1.
unit 参数是可选的,但最好指定它。它应该是一个字符串,表示直方图的单位。

您可以在 OpenTelemetry 文档中阅读有关直方图指标的更多信息。

上下计数器

“Up-Down Counter”是一种计数器指标,允许递增(上升)和递减(向下)操作。与只允许增量的常规计数器不同,上下计数器可以根据要跟踪的事件或状态增加或减少。

您可以使用此指标来衡量以下内容:

  • 活动连接数。

  • 队列中的项目数。

  • 在线用户数。

要创建上下计数器指标,请使用 logfire.metric_up_down_counter 功能:

import logfire

active_users = logfire.metric_up_down_counter(
    'active_users',
    unit='1',  # (1)!
    description='Number of active users'
)

def user_logged_in():
    active_users.add(1)

def user_logged_out():
    active_users.add(-1)
  1. unit 参数是可选的,但最好指定它。它应该是一个字符串,表示上下计数器的单位。如果度量是_无单位_的,则可以使用“1”。

您可以在 OpenTelemetry 文档中阅读有关 Up-Down Counter 指标的更多信息。

轨距

当您想要测量应用程序中特定状态或事件的当前值时,Gauge 指标特别有用。与计数器指标不同,仪表指标不会随着时间的推移累积值。

您可以使用此指标来衡量以下内容:

  • 当前温度。
  • 当前内存使用情况。

  • 当前活动连接数。

  • 当前在线用户数。

要创建仪表指标,请使用 logfire.metric_gauge功能:

import logfire

temperature = logfire.metric_gauge(
    'temperature',
    unit='°C',
    description='Temperature'
)

def set_temperature(value: float):
    temperature.set(value)

您可以在 OpenTelemetry 文档中阅读有关 Gauge 指标的更多信息。

回调指标

回调指标或可观察指标是一种创建根据时间间隔自动更新的指标的方法。

计数器回调

要创建计数器回调指标,请使用 logfire.metric_counter_callback 功能:

import logfire
from opentelemetry.metrics import CallbackOptions, Observable


def cpu_time_callback(options: CallbackOptions) -> Iterable[Observation]:
    observations = []
    with open("/proc/stat") as procstat:
        procstat.readline()  # skip the first line
        for line in procstat:
            if not line.startswith("cpu"):
                break
            cpu, user_time, nice_time, system_time = line.split()
            observations.append(
                Observation(int(user_time) // 100, {"cpu": cpu, "state": "user"})
            )
            observations.append(
                Observation(int(nice_time) // 100, {"cpu": cpu, "state": "nice"})
            )
            observations.append(
                Observation(int(system_time) // 100, {"cpu": cpu, "state": "system"})
            )
    return observations

logfire.metric_counter_callback(
    'system.cpu.time',
    unit='s',
    callbacks=[cpu_time_callback],
    description='CPU time',
)

可以在 OpenTelemetry 文档中阅读有关计数器指标的更多信息。

仪表回调

当您想要测量应用程序中特定状态或事件的当前值时,仪表度量特别有用。与计数器指标不同,仪表指标不会随着时间的推移累积值。

要创建仪表回调指标,请使用 logfire.metric_gauge_callback功能:

import logfire


def get_temperature(room: str) -> float:
    ...


def temperature_callback(options: CallbackOptions) -> Iterable[Observation]:
    for room in ["kitchen", "living_room", "bedroom"]:
        temperature = get_temperature(room)
        yield Observation(temperature, {"room": room})


logfire.metric_gauge_callback(
    'temperature',
    unit='°C',
    callbacks=[temperature_callback],
    description='Temperature',
)

您可以在 OpenTelemetry 文档中阅读有关 Gauge 指标的更多信息。

Up-Down 计数器回调

这是上下计数器指标的回调版本。

要创建上下计数器回调指标,请使用 logfire.metric_up_down_counter_callback 功能:

import logfire


def get_active_users() -> int:
    ...


def active_users_callback(options: CallbackOptions) -> Iterable[Observation]:
    active_users = get_active_users()
    yield Observation(active_users, {})


logfire.metric_up_down_counter_callback(
    'active_users',
    unit='1',
    callbacks=[active_users_callback],
    description='Number of active users',
)

您可以在 OpenTelemetry 文档中阅读有关 Up-Down Counter 指标的更多信息。

系统衡量指标

默认情况下,Logfire不会收集系统指标。

要启用指标,您只需要安装 logfire[system-metrics] extra:

pip install 'logfire[系统指标]'
rye add logfire -E 系统指标
poetry add 'logfire[系统指标]'

如果安装了 logfire[system-metrics] extra,Logfire 将自动收集系统指标。

要了解有关收集哪些系统指标的更多信息,请查看系统指标文档。


本文总阅读量