Metadata-Version: 2.4
Name: T-autolog
Version: 1.0.0
Summary: Zero-config auto-instrumentation logging for Python
License: MIT
Project-URL: Homepage, https://github.com/YOUR_USERNAME/autolog
Project-URL: Repository, https://github.com/YOUR_USERNAME/autolog
Project-URL: Issues, https://github.com/YOUR_USERNAME/autolog/issues
Keywords: logging,instrumentation,tracing,debugging,autolog
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: System :: Logging
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Provides-Extra: fastapi
Requires-Dist: starlette>=0.20; extra == "fastapi"
Provides-Extra: flask
Requires-Dist: flask>=2.0; extra == "flask"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Requires-Dist: httpx; extra == "dev"
Requires-Dist: fastapi; extra == "dev"
Requires-Dist: flask; extra == "dev"

# autolog

> Zero-config auto-instrumentation logging for Python. Drop one line into your entrypoint and every function call gets logged — inputs, outputs, duration, errors, and trace IDs. No changes to your business logic required.

---

## Features

- **Zero-touch mode** — patch an entire package at import time with one line
- **Decorator mode** — opt-in per function or class
- **Async-native** — supports `async def`, generators, and async generators
- **Sensitive data redaction** — automatically masks passwords, tokens, API keys
- **Trace IDs** — async-safe per-request correlation via `contextvars`
- **Structured output** — consistent log blocks with inputs, result, duration, error
- **FastAPI & Flask middleware** — HTTP request/response logging out of the box
- **Configurable via env vars** — no code changes needed to tune behavior
- **Windows-safe** — UTF-8 output even on Windows terminals

---

## Installation

```bash
pip install autolog
```

With optional framework support:

```bash
pip install "autolog[fastapi]"
pip install "autolog[flask]"
```

Install from source (development):

```bash
git clone https://github.com/YOUR_USERNAME/autolog.git
cd autolog
pip install -e ".[dev]"
```

---

## Quick Start

### Zero-touch — no changes to your code

Create a `run.py` next to your project and call `autolog.install()` before anything else:

```python
import autolog
autolog.install(["myapp"])

# your normal entrypoint, completely untouched
from myapp.main import main
main()
```

Every function in the `myapp` package is now logged automatically.

**Sample output:**

```
[2026-05-07 14:23:01.042] [INFO ] [billing.services.customers.get_customer]
  ▸ trace    : 3f4a1b2c-...
  ▸ inputs   : {"customer_id": "cust_123"}
  ▸ result   : {"id": "cust_123", "name": "Alice"}
  ▸ duration : 0.0031 s
────────────────────────────────────────────────
```

---

## Usage

### Zero-touch (import hook)

```python
import autolog

autolog.install(
    ["myapp", "utils"],   # list of packages to patch
    service="billing",    # optional: label shown in logs
    level="DEBUG",        # optional: minimum log level
    log_file="app.log",   # optional: mirror logs to a file
)
```

Must be called **before** importing the packages you want to log.

---

### Decorator — opt-in per function

```python
from autolog import log_function

@log_function
def calculate_tax(amount: float, rate: float) -> float:
    return amount * rate

@log_function
async def fetch_invoice(invoice_id: str):
    ...

# with options
@log_function(service="billing", level="DEBUG", log_file="billing.log")
def process_payment(payload: dict):
    ...
```

Works with sync, async, generators, and async generators.

---

### Decorator — opt-in per class

```python
from autolog import log_class

@log_class
class InvoiceService:
    def create(self, data): ...
    async def fetch(self, invoice_id): ...
    def _internal(self): ...     # skipped — underscore methods are excluded
```

Wraps all public methods. Handles `@staticmethod`, `@classmethod`, and `@property` correctly.

---

### Skip specific functions

```python
from autolog import no_log

@no_log
def hot_path():
    """This function will never be wrapped, even inside an auto-patched package."""
    ...
```

---

### Trace IDs

Correlate all log entries for a single request:

```python
from autolog import new_trace_id, get_trace_id

# at the start of a request / task
trace_id = new_trace_id()   # generates UUID4, stores in ContextVar

# anywhere downstream
trace_id = get_trace_id()   # returns current ID or "-"
```

Trace IDs are async-safe — each coroutine/task has its own context.

---

## Framework Middleware

### FastAPI

```python
from fastapi import FastAPI
from autolog.middleware.fastapi import AutoLogMiddleware

app = FastAPI()
app.add_middleware(AutoLogMiddleware, service="my-api")
```

Logs method, path, status code, inputs, and response for every HTTP request. Uses `BackgroundTask` so logging never blocks the response.

---

### Flask

```python
from flask import Flask
from autolog.middleware.flask import init_autolog

app = Flask(__name__)
init_autolog(app, service="my-api")
```

---

## Configuration

All options can be set via environment variables — no code changes needed:

| Env var | Default | Description |
|---|---|---|
| `AUTOLOG_LEVEL` | `INFO` | Minimum log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`) |
| `AUTOLOG_FILE` | — | Path to mirror logs to a file |
| `AUTOLOG_SERVICE` | package name | Service label shown in log lines |
| `AUTOLOG_DISABLE` | — | Set to `1` to disable all wrapping (e.g. in tests) |
| `NO_COLOR` | — | Set to `1` to disable ANSI color output |

Example:

```bash
AUTOLOG_LEVEL=DEBUG AUTOLOG_FILE=app.log python run.py
```

---

## Sensitive Data Redaction

The following argument names are automatically redacted in both inputs and outputs:

`password`, `passwd`, `token`, `secret`, `key`, `auth`, `credential`, `api_key`, `apikey`, `jwt`, `bearer`

```python
def login(username, password):
    ...

# logged as:
# ▸ inputs   : {"username": "alice", "password": "[REDACTED]"}
```

Redaction is recursive — works inside nested dicts, lists, and tuples.

---

## Log Output Format

Every log entry is a structured block:

```
[TIMESTAMP] [LEVEL] [module.function]
  ▸ trace    : <uuid>
  ▸ inputs   : {"arg": value, ...}
  ▸ result   : <value>           (on success)
  ▸ error    : <exception repr>  (on failure)
  ▸ duration : 0.0031 s
────────────────────────────────────────────────
```

---

## Running Tests

```bash
pip install -e ".[dev]"
pytest tests/ -v
```

---

## License

MIT
