Skip to content

Add Metrics

ThePydantic Logfirecan be used to collect metrics from your application and send them to the metrics backend.

Let's look at how to create and use metrics in an application.

import logfire

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

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

indicator type

Metrics are a good way to record numeric values where you want to see an aggregation of data (for example, over time) rather than a single value.

counter

The Counter indicator is particularly useful when you want to measure the frequency or number of occurrences of a particular event or state in your application.

You can use this metric to calculate the following:

  • The number of exceptions caught.

  • The number of requests received.

  • The number of items processed.

To create a counter metric, use the logfire.metric_counter function:

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. The unit parameter is optional, but it is best to specify it. It should be a string that represents the units of the counter. If the measure is_unitless_, then “1”。 can be used

can OpenTelemetry documentation Read more about counter indicators in.

histogram

Histogram metrics are especially useful when you want to measure the distribution of a set of values.

You can use this metric to measure:

  • The duration of the request.

  • Size of the file.

  • The number of items in the list.

To create histogram metrics, use the logfire.metric_histogram feature:

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 Parameter is optional, but it is best to specify it. It should be a string that represents the units of the histogram.

You can read more about histogram metrics in the OpenTelemetry documentation.

up-down counter

An "Up-Down Counter" is a counter indicator that allows both incrementing (up) and decrementing (down) operations. Unlike conventional counters, which allow only incrementing, an up-down counter can be incremented or decremented depending on the event or state being tracked.

You can use this metric to measure:

  • The number of active connections.

  • The number of items in the queue.

  • Number of online users.

To create an up-down counter metric, use the logfire.metric_up_down_counter function:

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. The unit parameter is optional, but it is best to specify it. It should be a string representing the units of the upper and lower counters. If the metric is_unitless_,“1”。 can be used

You can read more about the Up-Down Counter metric in the OpenTelemetry documentation.

gauge

The Gauge metric is especially useful when you want to measure the current value of a particular state or event in your application. Unlike counter metrics, gauge metrics do not accumulate values over time.

You can use this metric to measure:

  • The current temperature.
  • Current memory usage.

  • The number of currently active connections.

  • The number of users currently online.

To create gauge indicators, use the logfire.metric_gauge function:

import logfire

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

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

You can read more about the Gauge metric in the OpenTelemetry documentation.

Callback Indicator

Callback metrics or observable metrics are a way to create metrics that update automatically based on time intervals.

Counter Callback

To create a counter callback metric, use the logfire.metric_counter_callback function:

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',
)

can OpenTelemetry documentation Read more about counter indicators in.

Instrument pullback

Meter metrics are especially useful when you want to measure the current value of a specific state or event in your application. Unlike counter metrics, meter metrics do not accumulate values over time.

To create a meter callback metric, use logfire.metric_gauge_callback Function:

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',
)

you can OpenTelemetry documentation Read more about the Gauge indicator in.

Up-Down Counter Callback

This is the callback version of up and down counter indicator.

To create an up and down counter callback metric, use logfire.metric_up_down_counter_callback Function:

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',
)

You can read more about the Up-Down Counter metric in the OpenTelemetry documentation.

System measurement indicators

By default, LogfireSystem metrics are not collected.

To enable metrics, you only need to install logfire[system-metrics] extra:

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

If logfire[system-metrics] is installed extra, Logfirewill automatically collect system metrics.

To learn more about which system metrics are collected, check out the system metrics documentation.


本文总阅读量次