# Python metrics libraries

Python metrics libraries record numeric measurements from a running application, such as request counts, latencies, and queue lengths. An instrument such as a counter or histogram records each value with labels before an exporter sends the totals to a monitoring backend. These libraries let developers and on-call engineers see how production services behave over time.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [opentelemetry-api](#opentelemetry-api) | 721.7M | 2.7K | Oct 2026 | Apache-2.0 |
| [prometheus-client](#prometheus-client) | 175.4M | 4.4K | Jul 2026 | Apache-2.0 AND BSD-2-Clause |
| [Sentry SDK](#sentry-sdk) | 157.9M | 2.2K | Nov 2026 | MIT |
| [Datadog](#datadog) | 58.1M | 674 | Nov 2026 | BSD-3-Clause |
| [Logfire](#logfire) | 19.2M | 4.6K | Nov 2026 | MIT |
| [Powertools for AWS Lambda](#aws-lambda-powertools) | 15.6M | 3.3K | Nov 2026 | MIT |
| [statsd](#statsd) | 9.9M | 553 | Nov 2022 | MIT |
| [AWS Embedded Metrics](#aws-embedded-metrics) | 2.3M | 232 | Mar 2026 | Apache-2.0 |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[opentelemetry-api](#opentelemetry-api) has the most monthly downloads in this comparison, at 721.7M.

## Capabilities

| Library | Prometheus scrape output | Per-call metric sample rate |
| --- | --- | --- |
| [opentelemetry-api](#opentelemetry-api) | Via plugin | No |
| [prometheus-client](#prometheus-client) | Yes | No |
| [Sentry SDK](#sentry-sdk) | No | No |
| [Datadog](#datadog) | No | Yes |
| [Logfire](#logfire) | Via plugin | No |
| [Powertools for AWS Lambda](#aws-lambda-powertools) | No | No |
| [statsd](#statsd) | No | Yes |
| [AWS Embedded Metrics](#aws-embedded-metrics) | No | No |

## Libraries

### opentelemetry-api

[GitHub](https://github.com/open-telemetry/opentelemetry-python) · [PyPI](https://pypi.org/project/opentelemetry-api) · [Docs](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html)

Defines metric instruments and provider interfaces; an SDK supplies collection and exporters supply delivery.

- Downloads / mo: 721.7M
- Stars: 2.7K
- Last release: 1.45.2
- License: Apache-2.0
- Capabilities: [From the opentelemetry-api docs](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html)

**Strengths**

- **Separates instrumentation from collection.** Instrument library code without selecting its application’s metrics backend.
- **Associates attributes with measurements.** Attach dimensions to measurements through the metrics API and an installed SDK.

**Watch out for**

- **API alone records nothing.** Install and configure an SDK provider to collect measurements.
- **Global provider binds once.** Configure the provider once during application startup.

```sh
pip install opentelemetry-api opentelemetry-sdk
```

**vectorize-io/hindsight** (61.7K stars)

[vectorize-io/hindsight](https://github.com/vectorize-io/hindsight) 

```python
def record_operation_result(
    self,
    operation: str,
    bank_id: str,
    outcome: OperationOutcome,
    duration: float,
    source: str = "api",
    budget: str | None = None,
    max_tokens: int | None = None,
    memories_backend: str | None = None,
):
    """Record a single completed operation (duration + count) with its outcome.

    Direct (non-context-manager) recording for code paths that need explicit
    outcome control rather than the exception-based ``record_operation`` — e.g.
    the async worker, where deferrals/retries are not terminal outcomes and must
    not be counted as completions.
    """
    attributes = {
        "operation": operation,
        "source": source,
        **self._tenant_attrs(),
        **_backend_attrs(memories_backend_for(bank_id) if memories_backend is None else memories_backend),
    }
    if self._include_bank_id:
        attributes["bank_id"] = bank_id
    if budget:
        attributes["budget"] = budget
    if max_tokens:
        attributes["max_tokens"] = str(max_tokens)
    attributes["success"] = outcome.value

    # Record duration
    self.operation_duration.record(duration, attributes)

    # Record operation count
    self.operation_total.add(1, attributes)

```

[hindsight-api-slim/hindsight_api/metrics.py](https://github.com/vectorize-io/hindsight/blob/72e3454659bb94a345a27a2ad84f1c4b39b52572/hindsight-api-slim/hindsight_api/metrics.py#L772-L808) · [More projects using opentelemetry-api →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20opentelemetry-api%20native%20metrics%20counters%20histograms%20instrumentation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
reader = InMemoryMetricReader()
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
counter = metrics.get_meter("demo").create_counter("requests")
counter.add(1)

```

From [example.py](https://opentelemetry-python.readthedocs.io/en/latest/api/metrics.html)

### prometheus-client

[GitHub](https://github.com/prometheus/client_python) · [PyPI](https://pypi.org/project/prometheus-client) · [Docs](https://prometheus.github.io/client_python/instrumenting/counter/)

Records application metrics and exposes an HTTP endpoint for Prometheus to scrape.

- Downloads / mo: 175.4M
- Stars: 4.4K
- Last release: 0.26.0
- License: Apache-2.0 AND BSD-2-Clause
- Capabilities: [From the prometheus-client docs](https://prometheus.github.io/client_python/instrumenting/counter/)

**Strengths**

- **Serves a scrape endpoint.** Expose metrics over HTTP with the built-in server.
- **Groups observations with labels.** Separate related time series by method, endpoint, or other declared dimensions.

**Watch out for**

- **Summaries omit local quantiles.** Choose a histogram when queries need latency percentiles.
- **Multiprocess mode restricts features.** Custom collectors and label removal are unavailable in multiprocess deployments.

```sh
pip install prometheus-client
```

**rycus86/prometheus_flask_exporter** (686 stars)

[rycus86/prometheus_flask_exporter](https://github.com/rycus86/prometheus_flask_exporter) 

```python
def after_request(response):
    if hasattr(request, 'prom_do_not_track') or hasattr(request, 'prom_exclude_all'):
        return response

    if self.excluded_paths:
        if any(pattern.match(request.path) for pattern in self.excluded_paths):
            return response

    if hasattr(request, 'prom_start_time') and self._not_yet_handled('duration_reported'):
        total_time = max(default_timer() - request.prom_start_time, 0)

        if callable(duration_group):
            group = duration_group(request)
        else:
            group = getattr(request, duration_group)

        request_duration_labels = {
            'method': request.method,
            'status': _to_status_code(response.status_code),
            duration_group_name: group
        }
        request_duration_labels.update(labels.values_for(response))

        request_duration_metric.labels(**request_duration_labels).observe(total_time)

    if self._not_yet_handled('total_reported'):
        request_total_metric.labels(
            method=request.method, status=_to_status_code(response.status_code),
            **labels.values_for(response)
        ).inc()

    return response

```

[prometheus_flask_exporter/__init__.py](https://github.com/rycus86/prometheus_flask_exporter/blob/f2ba7ceb090647c6b6330ffe6c5b769139b2e10c/prometheus_flask_exporter/__init__.py#L464-L495) · [More projects using prometheus-client →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20prometheus-client%20native%20metrics%20counters%20histograms%20instrumentation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from prometheus_client import Counter
requests = Counter("demo_requests_total", "Processed requests")
requests.inc()

```

From [_index.md](https://github.com/prometheus/client_python/blob/master/prometheus_client/metrics.py)

### Sentry SDK

[GitHub](https://github.com/getsentry/sentry-python) · [PyPI](https://pypi.org/project/sentry-sdk) · [Docs](https://docs.sentry.io/platforms/python/metrics/)

Connects Python applications to Sentry.

- Downloads / mo: 157.9M
- Stars: 2.2K
- Last release: 2.75.0
- License: MIT
- Capabilities: [From the Sentry SDK docs](https://docs.sentry.io/platforms/python/metrics/)

```sh
pip install sentry-sdk
```

**Vocab-Apps/anki-hyper-tts** (292 stars)

[Vocab-Apps/anki-hyper-tts](https://github.com/Vocab-Apps/anki-hyper-tts) 

```python
def get_tts_audio_instrumented(self, source_text, voice: voice_module.TtsVoice_v3, options, audio_request_context):
    with sentry_sdk.new_scope() as sentry_scope:
        # inside this scope, we can set tags and context which will get unwound when this scope closes
        sentry_scope.set_context("audio_voice", {
            'name': voice.name,
            'voice_key': voice.voice_key,
            'service': voice.service
        })
        sentry_scope.set_context("audio_options", options)
        sentry_scope.set_context('audio_request', {
            'text': source_text
        })
        sentry_scope.set_context("audio_request_context", {
            'reason': audio_request_context.get_audio_request_reason_tag(),
            'batch_uuid': audio_request_context.get_batch_uuid_str(),
            'retry_count': audio_request_context.retry_count,
            'retry_max': audio_request_context.retry_max,
        })
        use_clt = self.use_cloud_language_tools(voice)
        sentry_scope.set_tags({
            'hypertts_pro': use_clt,
            'audio_service': voice.service,
            'audio_request_reason': audio_request_context.audio_request_reason.name,
            'final_attempt': audio_request_context.is_final_attempt()
        })

        metrics_attributes = {
            "service": voice.service,
            'hypertts_pro': use_clt,
            'reason': audio_request_context.get_audio_request_reason_tag()
        }

        transaction_name = f'{voice.service}'
        if use_clt:
            transaction_name = f'cloudlanguagetools_{voice.service}'
        current_txn = sentry_sdk.get_current_scope().transaction
        if current_txn is not None:
            cm = sentry_sdk.start_span(op="audio", name=transaction_name)
        else:
            cm = sentry_sdk.start_transaction(op="audio", name=transaction_name)
        with cm as transaction:
            try:
                # audio request metrics
                sentry_sdk.metrics.count(
                    "audio_request",
                    1,
                    attributes=metrics_attributes,
                )

                tts_start = time.time()
                result_audio = self.get_tts_audio_implementation(source_text, voice, options, audio_request_context)
                tts_duration_ms = (time.time() - tts_start) * 1000

                # success metrics
                sentry_sdk.metrics.count(
                    "audio_request_success",
                    1,
                    attributes=metrics_attributes,
                )

                sentry_sdk.metrics.distribution(
                    "audio_request_duration",
                    tts_duration_ms,
                    unit="millisecond",
                    attributes=metrics_attributes,
                )

                return result_audio
            except Exception as e:
                sentry_scope.set_tags({
                    'exception_type': type(e).__name__,
                    'error_retryable': getattr(e, 'retryable', None),
                    'is_audio_request_exception': True
                })
                sentry_scope.set_context("exception_type", {
                    'exception_type': type(e).__name__,
                    'error_retryable': getattr(e, 'retryable', None)
                })
                # group by default fingerprint + service so that the same
                # exception type from different services creates separate issues
                sentry_scope.fingerprint = ['{{ default }}', voice.service]
                # this the only place we capture audio request exceptions
                sentry_sdk.capture_exception(e)

                sentry_sdk.metrics.count(
                    "audio_request_failure",
                    1,
                    attributes={**metrics_attributes, 'exception_type': type(e).__name__},
                )

                # let the caller handle the exception as well (e.g. for retry logic)
                raise

```

[hypertts_addon/servicemanager.py](https://github.com/Vocab-Apps/anki-hyper-tts/blob/e5f48ec691b92bfe8d55e70814ddab44a1a34f97/hypertts_addon/servicemanager.py#L299-L390) · [More projects using Sentry SDK →](https://dashboard.exa.ai/playground/search?q=sentry-sdk%20GitHub%20projects)

**Quickstart**

```python
import os
import sentry_sdk
sentry_sdk.init(dsn=os.environ["SENTRY_DSN"])
sentry_sdk.metrics.count("demo.requests", 1)

```

From [metrics.py](https://github.com/getsentry/sentry-python/blob/79eec68cc1f5ed082774320ebd6a51b08c243fe6/sentry_sdk/metrics.py)

### Datadog

[GitHub](https://github.com/DataDog/datadogpy) · [PyPI](https://pypi.org/project/datadog) · [Docs](https://datadogpy.readthedocs.io/en/latest/)

Submits application metrics to the Datadog Agent through its DogStatsD client.

- Downloads / mo: 58.1M
- Stars: 674
- Last release: 0.56.0
- License: BSD-3-Clause
- Capabilities: [From the Datadog docs](https://datadogpy.readthedocs.io/en/latest/)

**Strengths**

- **Tags individual measurements.** Attach tags and a sample rate when incrementing counters.
- **Supports UDP and Unix sockets.** Choose the transport that fits the Agent deployment.

**Watch out for**

- **Requires a running Agent.** Provide a reachable Datadog Agent for DogStatsD metrics.
- **Buffered metrics need draining.** Wait for pending payloads before shutting down a buffered sender.

```sh
pip install datadog
```

**Quickstart**

```python
from datadog import DogStatsd
client = DogStatsd(host="127.0.0.1", port=8125)
client.increment("demo.requests")

```

From [index.rst](https://datadogpy.readthedocs.io/en/latest/) · [Find projects using Datadog →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20datadog%20native%20metrics%20counters%20histograms%20instrumentation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### Logfire

[GitHub](https://github.com/pydantic/logfire) · [PyPI](https://pypi.org/project/logfire) · [Docs](https://logfire.pydantic.dev/docs/reference/api/logfire/)

Provides the Pydantic Logfire SDK and command-line interface.

- Downloads / mo: 19.2M
- Stars: 4.6K
- Last release: 6.0.0
- License: MIT
- Capabilities: [From the Logfire docs](https://logfire.pydantic.dev/docs/reference/api/logfire/)

```sh
pip install logfire
```

**Haidra-Org/AI-Horde** (1.7K stars)

[Haidra-Org/AI-Horde](https://github.com/Haidra-Org/AI-Horde) 

```python
def record_request_assignment_pressure(
    *,
    gentype: str,
    evidence: str,
    might_stall: bool,
    dispatch_opportunities: int,
    lost_opportunities: int,
    returned_capacity: int,
    active_preceding_dispatches: int,
    arriving_preceding_work: float,
    returned_work: float,
) -> None:
    """Record bounded diagnostics for one assignment-pressure calculation."""

    counts = (
        dispatch_opportunities,
        lost_opportunities,
        returned_capacity,
        active_preceding_dispatches,
        arriving_preceding_work,
        returned_work,
    )
    if any(count < 0 for count in counts):
        raise ValueError("Assignment-pressure values must be non-negative")
    if lost_opportunities > dispatch_opportunities:
        raise ValueError("Lost opportunities cannot exceed compatible dispatch opportunities")
    if evidence not in REQUEST_ASSIGNMENT_PRESSURE_EVIDENCE:
        raise ValueError(f"Unknown assignment-pressure evidence state: {evidence}")

    histogram_attributes: dict[str, str | bool] = {
        "horde.gentype": gentype,
        "horde.might_stall": might_stall,
    }
    request_assignment_pressure_dispatch_opportunities.record(dispatch_opportunities, histogram_attributes)
    request_assignment_pressure_lost_opportunities.record(lost_opportunities, histogram_attributes)
    request_assignment_pressure_returned_capacity.record(returned_capacity, histogram_attributes)
    request_assignment_pressure_active_preceding.record(active_preceding_dispatches, histogram_attributes)
    request_assignment_pressure_arriving_work.record(arriving_preceding_work, histogram_attributes)
    request_assignment_pressure_returned_work.record(returned_work, histogram_attributes)
    if dispatch_opportunities > 0:
        request_assignment_pressure_lost_share.record(
            lost_opportunities / dispatch_opportunities,
            histogram_attributes,
        )
    request_assignment_pressure_samples.add(
        1,
        {
            **histogram_attributes,
            "horde.evidence": evidence,
        },
    )

```

[horde/metrics.py](https://github.com/Haidra-Org/AI-Horde/blob/80f649d59e4a5aaf7e94127889932cf74d5abd89/horde/metrics.py#L510-L560) · [More projects using Logfire →](https://dashboard.exa.ai/playground/search?q=logfire%20GitHub%20projects)

**Quickstart**

```python
import os
import logfire
logfire.configure(token=os.environ["LOGFIRE_TOKEN"])
counter = logfire.metric_counter("demo.requests")
counter.add(1)

```

From [README.md](https://logfire.pydantic.dev/docs/reference/api/logfire/)

### Powertools for AWS Lambda

[GitHub](https://github.com/aws-powertools/powertools-lambda-python) · [PyPI](https://pypi.org/project/aws-lambda-powertools) · [Docs](https://docs.powertools.aws.dev/lambda/python/latest/core/metrics/)

Implements serverless best practices in AWS Lambda functions.

- Downloads / mo: 15.6M
- Stars: 3.3K
- Last release: 3.41.0
- License: MIT
- Capabilities: [From the Powertools for AWS Lambda docs](https://docs.powertools.aws.dev/lambda/python/latest/core/metrics/)

```sh
pip install aws-lambda-powertools
```

**aws-samples/aws-serverless-ecommerce-platform** (1.1K stars)

[aws-samples/aws-serverless-ecommerce-platform](https://github.com/aws-samples/aws-serverless-ecommerce-platform) 

```python
@metrics.log_metrics(raise_on_empty_metrics=False)
@logger.inject_lambda_context
@tracer.capture_lambda_handler
def handler(event, _):
    """
    Lambda handler
    """

    order_id = event["detail"]["orderId"]

    logger.info({
        "message": "Received failed order {}".format(order_id),
        "orderId": order_id
    })

    payment_token = get_payment_token(order_id)
    cancel_payment(payment_token)
    delete_payment_token(order_id)

    # Add custom metrics
    amount_lost = event["detail"]["total"]

    metrics.add_dimension(name="environment", value=ENVIRONMENT)
    metrics.add_metric(name="paymentCancelled", unit=MetricUnit.Count, value=1)
    metrics.add_metric(name="amountLost", unit=MetricUnit.Count, value=amount_lost)

```

[payment/src/on_failed/main.py](https://github.com/aws-samples/aws-serverless-ecommerce-platform/blob/3b9ef36dd3e338c8ab697c2bcb1b672e064e303c/payment/src/on_failed/main.py#L64-L88) · [More projects using Powertools for AWS Lambda →](https://dashboard.exa.ai/playground/search?q=aws-lambda-powertools%20GitHub%20projects)

**Quickstart**

```python
from aws_lambda_powertools import Metrics
from aws_lambda_powertools.metrics import MetricUnit
metrics = Metrics(namespace="Demo")
metrics.add_metric(name="Requests", unit=MetricUnit.Count, value=1)
metrics.flush_metrics()

```

From [metrics.html](https://docs.powertools.aws.dev/lambda/python/latest/api/metrics/metrics.html)

### statsd

[GitHub](https://github.com/jsocol/pystatsd) · [PyPI](https://pypi.org/project/statsd) · [Docs](https://statsd.readthedocs.io/en/stable/reference.html)

Sends counters and timings from Python applications to a StatsD daemon.

- Downloads / mo: 9.9M
- Stars: 553
- Last release: 4.0.1
- License: MIT
- Capabilities: [From the statsd docs](https://statsd.readthedocs.io/en/stable/reference.html)

**Strengths**

- **Batches measurements into packets.** Use a pipeline to send several measurements together.
- **Prefixes metric names.** Apply a shared prefix when constructing the client.

**Watch out for**

- **Pipelines need thread isolation.** Create a separate pipeline for each thread.
- **Timings use milliseconds.** Convert durations before passing them to timing.

```sh
pip install statsd
```

**Quickstart**

```python
from statsd import StatsClient
client = StatsClient(host="127.0.0.1", port=8125)
client.incr("demo.requests")

```

From [README.rst](https://statsd.readthedocs.io/en/stable/reference.html) · [Find projects using statsd →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20statsd%20native%20metrics%20counters%20histograms%20instrumentation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### AWS Embedded Metrics

[GitHub](https://github.com/awslabs/aws-embedded-metrics-python) · [PyPI](https://pypi.org/project/aws-embedded-metrics)

Provides the AWS Embedded Metrics package for Python.

- Downloads / mo: 2.3M
- Stars: 232
- Last release: 3.5.0
- License: Apache-2.0
- Capabilities: [From the AWS Embedded Metrics docs](https://github.com/awslabs/aws-embedded-metrics-python)

```sh
pip install aws-embedded-metrics
```

**aws-samples/serverless-samples** (351 stars)

[aws-samples/serverless-samples](https://github.com/aws-samples/serverless-samples) 

```python
@metric_scope
def lambda_handler(event, context, metrics):
    route_key = event['routeKey']

    response_body = {'Message': 'Unsupported route'}
    status_code = 400
    headers = {'Content-Type': 'application/json'}

    # Put common business metrics using EMF
    metric_payload = {}
    metrics.put_dimensions({'Service': 'Locations'})
    metrics.put_metric('ProcessedLocations', 1, 'Count')
    metrics.set_property('requestId', event['requestContext']['requestId'])
    metrics.set_property('routeKey', event['routeKey'])

    try:
        # Get all locations
        if route_key == 'GET /locations':
            metric_payload['operation'] = 'GET'
            ddb_response = ddbTable.scan(Select='ALL_ATTRIBUTES')
            response_body = ddb_response['Items']
            status_code = 200
        # Location CRUD operations
        if route_key == 'GET /locations/{locationid}':
            metric_payload['operation'] = 'GET'
            metric_payload['locationid'] = event['pathParameters']['locationid']
            ddb_response = ddbTable.get_item(
                Key={'locationid': event['pathParameters']['locationid']}
            )
            if 'Item' in ddb_response:
                response_body = ddb_response['Item']
            else:
                response_body = {}
            status_code = 200
        if route_key == 'DELETE /locations/{locationid}':
            metric_payload['operation'] = 'DELETE'
            metric_payload['locationid'] = event['pathParameters']['locationid']
            ddbTable.delete_item(
                Key={'locationid': event['pathParameters']['locationid']}
            )
            response_body = {}
            status_code = 200
        if route_key == 'PUT /locations':
            request_json = json.loads(event['body'])
            request_json['timestamp'] = datetime.now().isoformat()
            if 'locationid' not in request_json:
                request_json['locationid'] = str(uuid.uuid1())
            metric_payload['operation'] = 'PUT'
            metric_payload['locationid'] = request_json['locationid']
            ddbTable.put_item(
                Item=request_json
            )
            response_body = request_json
            status_code = 200
    except Exception as err:
        status_code = 400
        response_body = {'Error:': str(err)}
        print(str(err))
    metrics.set_property("Payload", metric_payload)
    return {
        'statusCode': status_code,
        'body': json.dumps(response_body),
        'headers': headers
    }

```

[serverless-rest-api/python-http-cdk/src/api/locations.py](https://github.com/aws-samples/serverless-samples/blob/d8b80a19a88dbc596d2e2ead2c466fc2780f1eb0/serverless-rest-api/python-http-cdk/src/api/locations.py#L19-L82) · [More projects using AWS Embedded Metrics →](https://dashboard.exa.ai/playground/search?q=aws-embedded-metrics%20GitHub%20projects)

**Quickstart**

```python
from aws_embedded_metrics import metric_scope
@metric_scope
def record_request(metrics):
    metrics.put_metric("Requests", 1, "Count")
record_request()

```

From [README.md](https://github.com/awslabs/aws-embedded-metrics-python)

## FAQ

### Which Python metrics library should I use?

[opentelemetry-api](#opentelemetry-api) suits applications that want vendor-neutral instruments and a choice of backend. [prometheus-client](#prometheus-client) suits services that Prometheus scrapes over HTTP. [Powertools for AWS Lambda](#aws-lambda-powertools) suits Lambda functions that publish to CloudWatch.

### OpenTelemetry vs Prometheus: which should I use?

[opentelemetry-api](#opentelemetry-api) defines vendor-neutral instruments and leaves collection and export to a configured SDK. [prometheus-client](#prometheus-client) records labeled instruments in process and serves them in the Prometheus format over HTTP.

### What is Logfire?

[Logfire](#logfire) is the Python SDK and command-line interface for Pydantic Logfire. It provides instruments and readers compatible with OpenTelemetry.

### How do I add Prometheus metrics to a Python app?

[prometheus-client](#prometheus-client) creates labeled counters, histograms, and summaries in the application process. It then serves their values over HTTP for Prometheus to scrape.

### What is Powertools for AWS Lambda?

[Powertools for AWS Lambda](#aws-lambda-powertools) is a toolkit for Lambda functions with a metrics facade that writes the CloudWatch Embedded Metric Format by default.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python metrics libraries prometheus-client opentelemetry-api statsd datadog code examples counters latency instrumentation",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
