Skip to main content

Prometheus Redis Exporter (Python версия)

Python License

Prometheus экспортер для метрик Redis/Valkey, написанный на Python.

Описание

Это Python-версия redis_exporter от oliver006, предоставляющая базовый функционал для экспорта метрик Redis в формате Prometheus.

Оригинальный проект: https://github.com/oliver006/redis_exporter
Текущий проект: https://github.com/vpuhoff/redis-exporter

Реализованные возможности

  • ✅ Экспорт метрик через команду INFO
  • ✅ Поддержка проверки отдельных ключей
  • ✅ Поддержка паттернов ключей через SCAN
  • ✅ TLS соединения
  • ✅ Базовая аутентификация (username/password)
  • ✅ Graceful shutdown
  • ✅ Prometheus client library

Не реализовано (ограничения)

  • ❌ Multi-target scrape endpoint (/scrape)
  • ❌ Cluster discovery (/discover-cluster-nodes)
  • ❌ Поддержка кластеров Redis
  • ❌ Поддержка Sentinel
  • ❌ Stream metrics
  • ❌ Lua scripts
  • ❌ Key groups aggregation
  • ❌ Latency histograms

Требования

  • Python 3.11+
  • Redis 2.x - 8.x

Установка

Установка как пакет

# Из исходников
git clone https://github.com/vpuhoff/redis-exporter.git
cd redis-exporter
pip install -e .

# Или установить зависимости напрямую
pip install redis prometheus-client

Использование в вашем проекте

Если у вас уже есть Python проект с Prometheus метриками, вы можете использовать Redis Exporter как библиотеку:

from prometheus_client import REGISTRY
from exporter import RedisCollector, Options

# Создать и зарегистрировать Redis коллектор
options = Options(redis_addr="redis://localhost:6379", namespace="redis")
redis_collector = RedisCollector("redis://localhost:6379", options)
REGISTRY.register(redis_collector)

См. README_LIBRARY.md для подробных примеров интеграции в FastAPI, Flask, Django и другие фреймворки.

Использование

Базовый запуск

python main.py --redis.addr=redis://localhost:6379

С опциями

python main.py \
  --redis.addr=redis://localhost:6379 \
  --redis.password=mypassword \
  --check-keys="db0=user:*,db1=sessions:*" \
  --check-single-keys="db0=counter" \
  --log-level=DEBUG

Переменные окружения

export REDIS_ADDR=redis://localhost:6379
export REDIS_PASSWORD=mypassword
export REDIS_EXPORTER_CHECK_KEYS="db0=test:*"
export REDIS_EXPORTER_LOG_LEVEL=INFO

python main.py

Docker

Сборка образа

docker build -t redis-exporter-py .

Запуск контейнера

docker run -d \
  --name redis-exporter \
  -p 9121:9121 \
  -e REDIS_ADDR=redis://redis-host:6379 \
  redis-exporter-py

Docker Compose

# Запустить тестовое окружение
docker-compose -f docker-compose-py.yml up -d

# Проверить метрики
curl http://localhost:9121/metrics

Конфигурация Prometheus

Добавьте в prometheus.yml:

scrape_configs:
  - job_name: redis_exporter
    static_configs:
    - targets: ['localhost:9121']

Доступные флаги

Флаг Переменная окружения Описание
--redis.addr REDIS_ADDR Адрес Redis (по умолчанию: redis://localhost:6379)
--redis.user REDIS_USER Имя пользователя для аутентификации
--redis.password REDIS_PASSWORD Пароль для аутентификации
--namespace REDIS_EXPORTER_NAMESPACE Namespace для метрик (по умолчанию: redis)
--check-keys REDIS_EXPORTER_CHECK_KEYS Паттерны ключей для проверки через SCAN
--check-single-keys REDIS_EXPORTER_CHECK_SINGLE_KEYS Конкретные ключи для проверки
--connection-timeout REDIS_EXPORTER_CONNECTION_TIMEOUT Таймаут подключения в секундах
--web.listen-address REDIS_EXPORTER_WEB_LISTEN_ADDRESS Адрес HTTP сервера
--log-level REDIS_EXPORTER_LOG_LEVEL Уровень логирования (DEBUG/INFO/WARNING/ERROR)
--log-format REDIS_EXPORTER_LOG_FORMAT Формат логов (txt/json)
--debug - Включить отладочный вывод
--version - Показать версию и выйти

Экспортируемые метрики

Базовые метрики

  • redis_up - доступность Redis
  • redis_exporter_scrapes_total - общее количество сканирований
  • redis_exporter_scrape_duration_seconds - длительность сканирования
  • redis_exporter_last_scrape_error - ошибка последнего сканирования

Метрики Redis INFO

Основные категории метрик из команды INFO:

  • Server: uptime, процесс, потоки
  • Clients: подключенные клиенты, заблокированные клиенты
  • Memory: использование памяти, RSS, пиковое использование
  • Stats: операции в секунду, команды
  • Replication: статус репликации, offset
  • Keyspace: количество ключей по БД

Метрики ключей

При использовании --check-keys или --check-single-keys:

  • redis_key_size - размер ключа (количество элементов)
  • redis_key_value - значение ключа (если числовое)
  • redis_key_value_as_string - значение ключа как строка

Примеры использования

Мониторинг одного Redis

python main.py --redis.addr=redis://localhost:6379

Мониторинг с паролем

python main.py \
  --redis.addr=redis://localhost:6379 \
  --redis.password=secret

Мониторинг с проверкой ключей

python main.py \
  --redis.addr=redis://localhost:6379 \
  --check-single-keys="db0=active_users,db0=total_sessions" \
  --check-keys="db1=user:*"

TLS соединение

python main.py --redis.addr=rediss://localhost:6380

Тестирование

# Установить зависимости для разработки
uv pip install -e .

# Запустить тесты (если есть)
# pytest tests/

# Проверить метрики
curl http://localhost:9121/metrics

Разработка

Структура проекта

redis-exporter/
├── main.py                  # Точка входа (CLI)
├── pyproject.toml           # Зависимости Python
├── Dockerfile               # Docker образ
├── docker-compose.yml       # Docker Compose для тестирования
├── README.md                # Основная документация
├── README_LIBRARY.md        # Документация для использования как библиотека
├── .gitignore               # Git ignore файлы
├── LICENSE                  # MIT лицензия
├── exporter/                # Модули экспортера
│   ├── __init__.py
│   ├── config.py            # Конфигурация
│   ├── exporter.py          # Главный коллектор
│   ├── info.py              # Парсинг INFO
│   ├── keys.py              # Проверка ключей
│   ├── metrics.py           # Вспомогательные функции
│   └── redis_client.py      # Redis клиент
├── examples/                # Примеры использования как библиотеки
│   ├── __init__.py
│   ├── simple_example.py
│   ├── fastapi_example.py
│   ├── flask_example.py
│   ├── multiple_redis_example.py
│   └── custom_registry_example.py
└── contrib/                 # Дополнительные материалы
    ├── README.md            # Описание contrib
    ├── grafana_prometheus_redis_dashboard.json
    ├── grafana_prometheus_redis_dashboard_exporter_version_0.3x.json
    └── k8s-redis-and-exporter-deployment.yaml

Добавление новых метрик

  1. Добавьте метрику в metric_map_gauges или metric_map_counters в exporter/exporter.py
  2. Запустите тесты
  3. Обновите документацию

Ограничения по сравнению с Go-версией

  • Одновременный мониторинг только одного Redis
  • Нет поддержки кластеров
  • Нет поддержки Sentinel
  • Нет многопоточности для SCAN
  • Более медленная работа на больших нагрузках

Использование как библиотека

Redis Exporter может использоваться в вашем Python приложении для добавления Redis метрик к существующим Prometheus метрикам:

from prometheus_client import REGISTRY
from exporter import RedisCollector, Options

# Создать и зарегистрировать коллектор
options = Options(redis_addr="redis://localhost:6379", namespace="redis")
collector = RedisCollector("redis://localhost:6379", options)
REGISTRY.register(collector)

📚 Полная документация: См. папку docs/ со всей документацией проекта.

Лицензия

MIT License - см. файл LICENSE

Благодарности

Этот проект основан на oliver006/redis_exporter.

Контрибуции

Приветствуются! Откройте issue или создайте pull request.

Поддержка

Metadata

Release files for redis-exporter 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for redis-exporter 1.0.0
File Size Uploaded Provenance Actions
redis_exporter-1.0.0.tar.gz 72.5 kB With provenance Details for redis_exporter-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for redis-exporter 1.0.0
File Interpreter ABI Platform Actions
redis_exporter-1.0.0-py3-none-any.whl Python 3 none any Details for redis_exporter-1.0.0-py3-none-any.whl

Total release size: 90.9 kB

Release files / redis_exporter-1.0.0.tar.gz

Download URL redis_exporter-1.0.0.tar.gz
Size 72.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1080711ac4efcd61d0fc71886bf1c223a9c55aa62e7f93b241709bc88b4572c4
BLAKE2b-256 checksum
How to use checksums
a032574613aa0834934335d9b5fe676e5d92bf31de2efd49feac11775dba16ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 31, 2025.

Transparency log

Release files / redis_exporter-1.0.0-py3-none-any.whl

Download URL redis_exporter-1.0.0-py3-none-any.whl
Size 18.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7303aaae2094f76b41cf88437fe1e07c9843c829a22e1c69c5c6114b9886774a
BLAKE2b-256 checksum
How to use checksums
8accd3cbd6f510e7a88cc2a44f61eea24112b5fca8f49718ade2a5f17a63d5d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 31, 2025.

Transparency log

Security for redis-exporter 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for redis_exporter-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 31, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page