Metadata-Version: 2.5
Name: tracekit-sdk
Version: 0.1.0
Summary: Minimal zero-dependency Python observability SDK
Project-URL: Homepage, https://github.com/its-bismay/tracekit-sdk
Project-URL: Repository, https://github.com/its-bismay/tracekit-sdk
Project-URL: Issues, https://github.com/its-bismay/tracekit-sdk/issues
Author-email: its-bismay <2023ugee070@nitjsr.ac.in>
License: MIT
License-File: LICENSE
Keywords: error-tracking,monitoring,observability,sdk,tracing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# TraceKit

[![PyPI](https://img.shields.io/pypi/v/tracekit-sdk.svg)](https://pypi.org/project/tracekit-sdk/)
[![CI](https://github.com/its-bismay/tracekit/actions/workflows/ci.yml/badge.svg)](https://github.com/its-bismay/tracekit/actions/workflows/ci.yml)

A minimal, zero-dependency Python observability SDK — error tracking and performance timing, inspired by Sentry but far smaller.

**Package:** `tracekit-sdk` · **Import:** `tracekit` · **Python:** 3.12+ · **Dependencies:** none (stdlib only)

---

## 30-second quickstart

```bash
pip install tracekit-sdk        # or: uv add tracekit-sdk
```

```python
import tracekit

tracekit.init(
    output="console",           # "console" | "file:events.jsonl" | "http://..."
    environment="production",
    release="1.0.0",
)

# Manual capture
tracekit.capture_message("App started", level="info")

try:
    result = 1 / 0
except ZeroDivisionError:
    tracekit.capture_exception()   # captures current exception automatically

# Performance tracing
@tracekit.trace
def fetch_user(user_id: int) -> dict:
    ...  # your code here

# or with a context manager
with tracekit.span("db.query"):
    ...

tracekit.flush()   # ensure all events are delivered before exit
```

---

## Output modes

### Console (default)

```
[TraceKit 2026-11-28 10:15:30] ERROR   ZeroDivisionError: division by zero  app.py:12 in main
[TraceKit 2026-11-28 10:15:30] INFO    App started
[TraceKit 2026-11-28 10:15:30] SPAN    fetch_user (1.42ms) ok
```

### File (JSONL)

```python
tracekit.init(output="file:events.jsonl")
```

Each event is one JSON object per line. Use `tracekit tail` to watch it live:

```bash
tracekit tail events.jsonl
```

### HTTP (local viewer or remote ingest)

```python
tracekit.init(output="http://127.0.0.1:8765/ingest")
```

Start the built-in viewer:

```bash
tracekit serve --port 8765
# Open http://127.0.0.1:8765 in your browser — auto-refreshes every 2 s
```

---

## Full API reference

### `tracekit.init(...)`

| Parameter | Type | Default | Description |
|---|---|---|---|
| `output` | `str` | `"console"` | Delivery target (see Output modes above) |
| `environment` | `str` | `"production"` | Attached to every event |
| `release` | `str \| None` | `None` | App version string |
| `sample_rate` | `float` | `1.0` | Fraction of **span** events to keep (0.0–1.0); errors are always kept |
| `ignore_errors` | `list` | `[]` | Exception classes or name strings to silently drop |
| `before_send` | `callable \| None` | `None` | Called with every event dict; return `None` to drop |
| `debug` | `bool` | `False` | Print internal SDK errors to stderr |

### Automatic exception capture

After `init()`, unhandled exceptions are captured automatically:

```python
# Main thread — via sys.excepthook
# Worker threads — via threading.excepthook
# asyncio tasks — call once after creating your loop:
tracekit.install_asyncio_hook(loop)
```

### Scope enrichment

```python
tracekit.set_user(id="42", email="alice@example.com")
tracekit.set_tag("region", "eu-west-1")
tracekit.add_breadcrumb("Payment initiated", category="checkout")
```

All subsequent events from the same thread / async task carry these fields.

### Performance tracing

```python
# Decorator — sync and async both supported
@tracekit.trace
async def process_order(order_id: int) -> None: ...

@tracekit.trace(name="custom.span.name")
def expensive_query() -> list: ...

# Context manager
with tracekit.span("external.api.call"):
    response = requests.get(url)
```

### Filtering and scrubbing

```python
def drop_health_checks(event: dict) -> dict | None:
    if event.get("message") == "GET /health":
        return None          # drop
    return event             # keep

tracekit.init(
    before_send=drop_health_checks,
    ignore_errors=[ConnectionResetError, "TimeoutError"],
    sample_rate=0.1,         # keep 10 % of spans
)
```

Fields named `password`, `secret`, `token`, `api_key`, `authorization`, `cookie` etc. are automatically replaced with `[Filtered]` before any event leaves the process.

### Python `logging` integration

```python
import logging
from tracekit.integrations.logging import TraceKitHandler

tracekit.init(...)
logging.getLogger().addHandler(TraceKitHandler())

logging.error("Something broke")        # → error event
logging.warning("Slow query: 2.3 s")   # → breadcrumb
logging.info("User signed in")          # → breadcrumb
```

### CLI tools

```bash
tracekit tail events.jsonl          # follow a JSONL file live
tracekit serve --port 8765          # start the HTML viewer
```

---

## Architecture

```
Your app
  │
  ├─ tracekit.capture_exception / capture_message
  ├─ @tracekit.trace / tracekit.span()
  └─ sys/threading/asyncio hooks
           │
           ▼
       Client
       ├─ apply_filters()   ← sample_rate, ignore_errors, scrubbing, before_send
       └─ Transport.enqueue()   ← non-blocking, drops if queue full (max 1000)
                │
                ▼  (single daemon thread)
            Sink.emit()
            ├─ ConsoleSink   → stderr (ANSI colour)
            ├─ FileSink      → JSONL file (open/write/close per event)
            └─ HttpSink      → POST batches ≤20 events, retry ×3 with backoff
```

**Resource limits (PRD §1.10)**

| Resource | Limit |
|---|---|
| Background threads | 1 daemon thread |
| Event queue | 1 000 slots (drop when full, never block) |
| Stack frames per error | 50 (innermost kept) |
| String field length | 1 000 chars (truncated with `…`) |
| Breadcrumbs per context | 20 (oldest dropped) |
| HTTP batch size | 20 events |
| HTTP retry attempts | 3 × exponential backoff (0.5 → 1.0 → 2.0 s) |
| Viewer ring buffer | 500 events |

---

## Development

```bash
git clone https://github.com/yourname/tracekit
cd tracekit
uv sync --dev

uv run pytest -v              # run tests
uv run ruff check .           # lint
uv build                      # build wheel → dist/
```

> **Note:** Phase 6 network tests use loopback TCP — run `uv run pytest -v` outside any sandbox environment that restricts `bind()`/`connect()`.

---

## Releasing

Releases are published automatically to PyPI via GitHub Actions Trusted Publishing when a GitHub release is published:

1. Bump `version` in `pyproject.toml`.
2. Run `uv lock` to update the lockfile.
3. Commit the changes: `git commit -am "Release vX.Y.Z"`.
4. Tag the commit: `git tag vX.Y.Z`.
5. Push the commit and tag: `git push && git push --tags`.
6. Create and publish a GitHub Release for tag `vX.Y.Z`.

---

## License

MIT
