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/Ananta-Ops/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.1.tar.gz (11.6 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.1-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: opslogger-1.0.1.tar.gz
  • Upload date:
  • Size: 11.6 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.1.tar.gz
Algorithm Hash digest
SHA256 5c787060555caaf55a3ed55e151e1d4eac9775eeff3262ada8793593c780b73d
MD5 b62f612b4d389e83466ec59b6d2d37a8
BLAKE2b-256 e7c8626ce1c703af387f843f04ca9bd29bedbe524d93dbae8cd9bb5e07830f72

See more details on using hashes here.

File details

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

File metadata

  • Download URL: opslogger-1.0.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e2c91216791e1283cfbf9f7384d6394be241de0159364e2f7f5a9c11447f8c1e
MD5 588ae30ff39d318437375f37ff5f73cc
BLAKE2b-256 a1398038b23c380bcd7b5cd4d4c21605f6ef99efe6b74f7a5d2265af61d7478e

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