๐๏ธ Prism View - Structured logging, error handling, and observability for Prism applications
Project description
๐๏ธ Prism View
Structured logging, error handling, and observability for Python applications.
Part of Project Prism - a cross-language platform engineering suite.
What is Prism View?
Prism View provides everything you need for production-ready logging and error handling:
- Dual-mode logging - Pretty terminal output (dev) vs structured JSON (prod)
- Custom error taxonomy - Define error codes, categories, and recovery hints
- Context tracking - Automatic trace IDs, user context, operation timing
- Secret scrubbing - Automatic PII/password redaction in logs
- Framework integration - Works with FastAPI, Flask, and standard library logging
Installation
pip install prism-view
Quick Start
1. Initialize Logging
from prism.view import setup_logging, get_logger, LogContext
# Initialize (shows banner in dev mode)
setup_logging(mode="dev")
# Create a logger
logger = get_logger("my-app")
# Set service context (once at startup)
LogContext.set_service(name="my-app", version="1.0.0", environment="development")
2. Log with Context
# Simple logging
logger.info("Server started", port=8080)
logger.warning("High memory usage", percent=85)
logger.error("Connection failed", host="db.example.com")
# With request context (trace_id auto-generated if not provided)
with LogContext.request(method="POST", path="/api/orders"):
with LogContext.user(user_id="user-123"):
logger.info("Processing order", order_id="ord-456")
# Logs include: trace_id, user_id, method, path
3. Track Operation Duration
with LogContext.operation("fetch_user_data"):
# ... do work ...
logger.info("Fetched user") # Includes duration_ms automatically
Custom Errors
Define errors with codes, categories, and recovery hints:
from prism.view import PrismError, ErrorSeverity, ErrorCategory
class PaymentError(PrismError):
"""Payment processing failed."""
code = (1001, "PAY", "PAYMENT_FAILED")
category = ErrorCategory.EXTERNAL
severity = ErrorSeverity.ERROR
retryable = True
max_retries = 3
# Raise with details and suggestions
raise PaymentError(
"Card declined",
details={"card_last4": "1234", "amount": 99.99},
suggestions=["Try a different card", "Check card balance"]
)
Errors automatically capture:
- Current
LogContext(trace_id, user_id, etc.) - Stack location (file, line, function)
- Cause chain for nested exceptions
- Timestamp
Dev vs Prod Mode
Set mode via environment variable or code:
export PRISM_LOG_MODE=prod # or "dev"
setup_logging(mode="prod") # Explicit mode
Dev mode - Colorful, human-readable:
12:34:56.789 โน๏ธ INFO [my-app] Server started | port=8080 trace_id=abc-123
Prod mode - Structured JSON for log aggregation:
{"ts": "2025-01-15T12:34:56.789Z", "level": "INFO", "logger": "my-app", "msg": "Server started", "port": 8080, "trace_id": "abc-123"}
Secret Scrubbing
Sensitive data is automatically redacted:
from prism.view import scrub
data = {
"username": "alice",
"password": "secret123", # Will be redacted
"api_key": "sk_live_xxx", # Will be redacted
"config": {"db_password": "hunter2"} # Nested - will be redacted
}
safe_data = scrub(data)
# {"username": "alice", "password": "[REDACTED]", "api_key": "[REDACTED]", ...}
The logger automatically scrubs all output. Built-in patterns detect:
- Passwords, secrets, tokens, API keys
- JWT tokens, Bearer tokens
- AWS access keys
- Credit card numbers
Framework Integration
FastAPI
from fastapi import FastAPI, Request
from prism.view import setup_logging, get_logger, LogContext
app = FastAPI()
setup_logging(mode="dev")
logger = get_logger("api")
@app.middleware("http")
async def add_context(request: Request, call_next):
with LogContext.request(method=request.method, path=request.url.path):
return await call_next(request)
@app.get("/users/{user_id}")
async def get_user(user_id: str):
logger.info("Fetching user", user_id=user_id)
return {"user_id": user_id}
Flask
from flask import Flask, g
from prism.view import setup_logging, get_logger, LogContext
app = Flask(__name__)
setup_logging(mode="dev")
logger = get_logger("api")
@app.before_request
def before_request():
g.ctx = LogContext.request(method=request.method, path=request.path)
g.ctx.__enter__()
@app.teardown_request
def teardown_request(exc):
if hasattr(g, 'ctx'):
g.ctx.__exit__(None, None, None)
See examples/ for complete integration examples.
API Reference
Logging
| Function | Description |
|---|---|
setup_logging(mode, palette, show_banner) |
Initialize the logging system |
get_logger(name) |
Get a logger instance |
Logger.info/debug/warning/error/critical() |
Log at various levels |
Logger.with_context(**kwargs) |
Create child logger with bound context |
Context
| Function | Description |
|---|---|
LogContext.set_service(name, version, ...) |
Set global service context |
LogContext.request(trace_id, method, ...) |
Request-scoped context |
LogContext.user(user_id, ...) |
User-scoped context |
LogContext.operation(name) |
Operation with duration tracking |
LogContext.batch(batch_id, total_items) |
Batch processing context |
LogContext.get_current() |
Get merged current context |
Errors
| Class/Function | Description |
|---|---|
PrismError |
Base exception with codes, context, recovery hints |
ErrorCategory |
Enum: CONFIGURATION, SECURITY, NETWORK, etc. |
ErrorSeverity |
Enum: DEBUG, INFO, WARNING, ERROR, CRITICAL |
format_exception(exc, mode) |
Format exception for display |
Scrubbing
| Function | Description |
|---|---|
scrub(data) |
Scrub sensitive data from dict |
Scrubber.add_key_pattern(key) |
Add custom sensitive key |
Scrubber.add_value_pattern(name, regex) |
Add custom value pattern |
Examples
The examples/ directory contains runnable examples:
01_basic_logging.py- Getting started with logging02_custom_errors.py- Defining custom error classes03_context_tracking.py- Request, user, and operation context04_secret_scrubbing.py- PII/secret redaction05_custom_palette.py- Color themes and styling06_error_recovery.py- Retry logic and circuit breakers07_batch_processing.py- Batch context and chunked processingfastapi_middleware.py- FastAPI integrationflask_integration.py- Flask integration
Part of Project Prism
Prism View is part of Project Prism, a cross-language platform engineering suite:
โโโโโโโโโโโโโโโโโโโ
โ prism-config โ Settings & Secrets Foundation
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโ
โ prism-view โ Logging & Error Handling โ You are here
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโ
โ prism-guard โ Auth & PQC Crypto
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโ
โ prism-data โ Persistence & Migrations
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโ
โ prism-api โ HTTP Standards & DTOs
โโโโโโโโโโฌโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโ
โ prism-boot โ Service Lifecycle
โโโโโโโโโโโโโโโโโโโ
| Library | Description | Status |
|---|---|---|
| prism-config | Typed configuration with secret resolution | Available |
| prism-view | Structured logging and error handling | v1.0.0 |
| prism-guard | Authentication and PQC-ready crypto | Coming soon |
| prism-data | Database access and migrations | Coming soon |
| prism-api | HTTP envelopes and DTO standards | Coming soon |
| prism-boot | Application lifecycle management | Coming soon |
Development
# Clone
git clone https://github.com/lukeudell/prism-view.git
cd prism-view
# Setup (creates venv, installs deps)
./setup-dev.sh # Linux/Mac
.\setup-dev.ps1 # Windows
# Run tests
pytest
# Run with coverage
pytest --cov=src/prism/view --cov-report=term-missing
License
MIT License - see LICENSE for details.
Contributing
Contributions welcome! Please see the Project Prism repository for contribution guidelines.
Made with ๐ as part of Project Prism
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file prism_view-1.0.0.tar.gz.
File metadata
- Download URL: prism_view-1.0.0.tar.gz
- Upload date:
- Size: 103.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d5de8c2cf0d87d968d1c00ea541aeed6472be44a20e9d2a9172ea2e1dcda35b6
|
|
| MD5 |
a4fc8e633f6737c99a3b477884fa2625
|
|
| BLAKE2b-256 |
60355f35347e0d1717c70152bb54a1ff453d9632172f3f67aaa7b2fd1942adb5
|
Provenance
The following attestation bundles were made for prism_view-1.0.0.tar.gz:
Publisher:
publish.yml on lukeudell/prism-view
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
prism_view-1.0.0.tar.gz -
Subject digest:
d5de8c2cf0d87d968d1c00ea541aeed6472be44a20e9d2a9172ea2e1dcda35b6 - Sigstore transparency entry: 747621567
- Sigstore integration time:
-
Permalink:
lukeudell/prism-view@7558b5c3ec874e513ad25d891f5cdd7d52b4cb32 -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/lukeudell
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7558b5c3ec874e513ad25d891f5cdd7d52b4cb32 -
Trigger Event:
release
-
Statement type:
File details
Details for the file prism_view-1.0.0-py3-none-any.whl.
File metadata
- Download URL: prism_view-1.0.0-py3-none-any.whl
- Upload date:
- Size: 43.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4ce59c38a3f6a73880d58d2e92d9adaf1c1e80e7904d9bdee1824821734c294c
|
|
| MD5 |
8af9a94aa3b8c7d88cf3368d2df8fa70
|
|
| BLAKE2b-256 |
3de6f9721ebea1b106b20822814fd6baf9b7608737aaf9af192ba74138f12e64
|
Provenance
The following attestation bundles were made for prism_view-1.0.0-py3-none-any.whl:
Publisher:
publish.yml on lukeudell/prism-view
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
prism_view-1.0.0-py3-none-any.whl -
Subject digest:
4ce59c38a3f6a73880d58d2e92d9adaf1c1e80e7904d9bdee1824821734c294c - Sigstore transparency entry: 747621569
- Sigstore integration time:
-
Permalink:
lukeudell/prism-view@7558b5c3ec874e513ad25d891f5cdd7d52b4cb32 -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/lukeudell
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7558b5c3ec874e513ad25d891f5cdd7d52b4cb32 -
Trigger Event:
release
-
Statement type: