Metadata-Version: 2.4
Name: opslogger
Version: 1.0.0
Summary: Structured, context-aware JSON logging for Python backend services.
Home-page: https://github.com/AnantaOps/OpsLogger-python
Author: AnantaOps
Author-email: AnantaOps <hello@anantaops.dev>
License: MIT License
        
        Copyright (c) 2025 AnantaOps
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/AnantaOps/OpsLogger-python
Project-URL: Repository, https://github.com/AnantaOps/OpsLogger-python
Keywords: logging,structured,json,observability,ops,backend
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Logging
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# 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:

```json
{
  "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 level** — `jq '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

```bash
# 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

```python
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:

```python
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

```python
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

```python
# 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

```bash
python examples/main.py
```

---

## Running Tests

```bash
# 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](./LICENSE) for the full text.

---

Built with ❤️ by [AnantaOps](https://github.com/AnantaOps)
