Skip to main content

Structured, context-aware JSON logging for Python backend services.

Project description

OpsLogger (Python)

Structured, context-aware JSON logging for Python backend services.
The first Python library from AnantaOps — built for developers who care about observability.


Why Structured Logging Matters

Plain-text logs are a liability at scale. When your service runs in containers, Kubernetes, or any cloud environment, every log aggregator (Datadog, Loki, CloudWatch, ELK) works best with machine-parseable, one-JSON-object-per-line output.

OpsLogger emits exactly that:

{
  "timestamp": "2025-03-14T10:22:01.123456+00:00",
  "level": "ERROR",
  "service": "PaymentService",
  "message": "Gateway timeout",
  "request_id": "req-abc-12345",
  "error": "ConnectionError: dial tcp: connection refused",
  "traceback": "Traceback (most recent call last): ...",
  "extra": {"gateway": "stripe", "retried": true}
}

Benefits at a glance:

  • Filter by leveljq 'select(.level=="ERROR")'
  • Trace a single request — filter on request_id
  • Alert on field values — no regex fragility
  • Drop into any log shipper — Fluent Bit, Logstash, Vector, etc.

Installation

# From PyPI (once published)
pip install opslogger

# From source / local development
git clone https://github.com/AnantaOps/OpsLogger-python.git
cd OpsLogger-python
pip install -e .

Requires Python 3.10+ · Zero external runtime dependencies.


Quick Start

from opslogger import OpsLogger

log = OpsLogger(service_name="OrderService")

log.debug("Cache lookup", extra={"key": "user:42"})
log.info("Service ready", extra={"env": "prod", "port": 8080})
log.warning("High memory", extra={"used_mb": 920})
log.error("Gateway timeout", error=ConnectionError("refused"))
log.critical("Disk full — writes disabled")

Request ID Tracing

Attach a request ID to every log entry in a request lifecycle:

def handle_order(request_id: str):
    log.info("Request received", request_id=request_id, extra={"path": "/api/orders"})
    log.info("Order created",    request_id=request_id, extra={"order_id": "ord-99"})
    log.error("Payment failed",  request_id=request_id, error=exc)

Every entry in the same request shares the same request_id, making end-to-end tracing trivial.


Log Levels

Method Level Use when
debug() DEBUG Verbose diagnostics — development only
info() INFO Normal operational events
warning() / warn() WARNING Recoverable, worth monitoring
error() ERROR Failures that need investigation
critical() CRITICAL Catastrophic failures

Custom Options

from opslogger import OpsLogger, LogLevel

# Only WARNING and above, write to a file, suppress console
log = OpsLogger(
    service_name="WorkerService",
    min_level=LogLevel.WARNING,
    console=False,
    log_file="/var/log/app/worker.log",
)

API Reference

# Construction
OpsLogger(
    service_name: str,
    *,
    min_level: LogLevel = LogLevel.DEBUG,   # minimum severity to emit
    console: bool = True,                   # write to stderr
    log_file: str | Path | None = None,     # also write to this file
)

# Logging methods
log.debug(message, *, request_id=None, extra=None)
log.info(message, *, request_id=None, extra=None)
log.warning(message, *, request_id=None, extra=None)   # also: log.warn(...)
log.error(message, *, error=None, request_id=None, extra=None)
log.critical(message, *, error=None, request_id=None, extra=None)

# Runtime control
log.set_min_level(level: LogLevel)
log.close()          # release file handles

# Context manager
with OpsLogger("MyService", log_file="app.log") as log:
    log.info("inside context")

Project Structure

OpsLogger-python/
├── opslogger/
│   ├── __init__.py        ← Public API surface
│   └── logger.py          ← Core engine
├── examples/
│   └── main.py            ← Runnable usage scenarios
├── tests/
│   └── test_logger.py     ← 25+ unit tests
├── setup.py               ← pip-installable package config
├── LICENSE                ← MIT
└── README.md

Running Examples

python examples/main.py

Running Tests

# Using pytest (recommended)
pip install pytest
pytest tests/ -v

# Using stdlib unittest
python -m unittest discover tests -v

License

MIT License — Copyright (c) 2025 AnantaOps

See LICENSE for the full text.


Built with ❤️ by AnantaOps

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

opslogger-1.0.0.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

opslogger-1.0.0-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file opslogger-1.0.0.tar.gz.

File metadata

  • Download URL: opslogger-1.0.0.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for opslogger-1.0.0.tar.gz
Algorithm Hash digest
SHA256 bf0bf03b4fd4426d45df2aad6829a98b6a03c82c30b2a20290f8032599c4984e
MD5 694d31a5178ec8b847e7b076b966a994
BLAKE2b-256 c2c412e0aa0f936f177eb3b8c5f220a3dab77c21d032bf128c1f5828f2d8cd45

See more details on using hashes here.

File details

Details for the file opslogger-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: opslogger-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for opslogger-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d3493dc5a06ed17970cac8a343ecad56c0c455dae3a9b91d2cd04e258abef97f
MD5 c82f5ad49a85bd8f8b96560d567bb47a
BLAKE2b-256 e7a42cd07ee40059109495b44b08002e6edc0d2ac6754abe48d51a56d35b7552

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page