# NatiLog — Logging library with API and frontend viewer

NatiLog is a Python/Django library to record application events (DEBUG, INFO, WARNING, ERROR, CRITICAL) to a backend API and visualize them in a frontend.

- Python client: `natilog/natilog-lib/nati_log/client.py`
- Django middleware: `natilog/natilog-lib/nati_log/middleware.py`
- Tests: `natilog/natilog-lib/tests/`

## Features

- Token-based auth (login returns `access`), automatic refresh on HTTP 401.
- Application state check before sending events (`/api/aplicaciones/{id}/`).
- ISO 8601 timestamp auto-fill if not provided.
- Safe behavior: if app is inactive or token cannot be obtained, events are omitted.

## Install

- Library (editable):
- Run: `pip install nati_log`

## Configuration (Django)

Add `NATILOG` to `settings.py` and register the middleware.

- Example:
- `NATILOG = {"API_URL": "http://localhost/api", "API_URL_LOGIN": "http://localhost/api/auth/usuarios/login/", "APP_ID": 5, "USERNAME": "user", "PASSWORD": "pass", "EVENT_LEVELS": {"DEBUG": True, "INFO": True, "WARNING": True, "ERROR": True, "CRITICAL": True}}`
- `MIDDLEWARE += ["nati_log.middleware.NatiLogMiddleware"]`

The middleware logs:
- DEBUG on every request.
- INFO for 2xx responses.
- WARNING for 3xx responses.
- ERROR for 4xx responses.
- CRITICAL for 5xx responses.

## Usage (Python)

Create a client and send events.

- Example:
- `from nati_log.client import NatiLogClient`
- `c = NatiLogClient(api_url="http://localhost/api", api_url_login="http://localhost/api/auth/usuarios/login/", app_id=5, username="user", password="pass")`
- `c.info("Startup OK", datos={"version": "1.0.0"})`
- `c.error("Processing failed", datos={"job_id": 123})`

## API contract

Expected endpoints:
- Login: `POST /api/auth/usuarios/login/` → returns JSON with `access` token.
- App state: `GET /api/aplicaciones/{id}/` → returns JSON with `estado` boolean.
- Event: `POST /api/evento/` → accepts JSON `{aplicacion, tipo_evento, mensaje, datos, fecha}` and returns 201 + JSON.

Notes:
- On 401 when posting an event, the client refreshes the token and retries once.
- If app state is inactive or token fetch fails, the client returns `{"detail": "Aplicación inactiva. Evento omitido."}` and does not send the event.

## Frontend

Any frontend can consume the backend API to list and filter events. Point it to the same base `API_URL` used by the client.

## Tests

Run tests on Linux:

- `cd natilog/natilog-lib`
- `pytest`

Coverage includes:
- Token refresh on 401.
- App inactive behavior.
- Timestamp formatting.
- Middleware level filtering and request/response mapping.