error-handling-logging-patterns
Skill17 starsChanged 5 months agoApache-2.0Archived repositoryView on GitHub
Implement structured logging, error hierarchies, and observability patterns for production systems. Covers structured JSON logging, error classification, correlation IDs, and alerting integration. Triggers on logging architecture, error handling strategy, or observability requests.
1 other project uses a version of this.
Other versions1 project uses a version of this.
Word for word · 1
- organvm-iv-taxis/a-i--skills★ 17100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository170 other files it gives its agents.
- AGENTS.mdAGENTS.md
- docs/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- algorithmic-artSkill
- audio-engineering-patternsSkill
- canvas-designSkill
- creative-writing-craftSkill
- generative-art-algorithmsSkill
- generative-art-deploymentSkill
- generative-music-composerSkill
- interactive-theatre-designerSkill
- modular-synthesis-philosophySkill
- movement-notation-systemsSkill
- narratological-algorithmsSkill
- natural-center-extractionSkill
- react-three-fiber-patternsSkill
- reality-tv-narrative-analyzerSkill
- script-analysis-dramaturgicalSkill
- theme-factorySkill
- three-js-interactive-builderSkill
- corpus-persona-extractionSkill
- data-ingestion-pipelineSkill
- data-pipeline-architectSkill
- data-storytelling-analystSkill
- market-gap-analysisSkill
- ml-experiment-trackerSkill
- prompt-atom-formalizationSkill
- sql-query-optimizerSkill
- systemic-product-analystSkill
- time-series-analystSkill
- accessibility-patternsSkill
- agent-testing-patternsSkill
- api-design-patternsSkill
- artifacts-builderSkill
- backend-implementation-patternsSkill
- browser-extension-patternsSkill
- cli-tool-designSkill
- code-refactoring-patternsSkill
- code-review-checklistSkill
- coding-standards-enforcerSkill
- community-platform-patternsSkill
- configuration-managementSkill
- continuous-learning-agentSkill
- data-backup-patternsSkill
- database-migration-patternsSkill
- deployment-cicdSkill
- docker-containerizationSkill
- dotfile-systems-architectSkill
- fastapi-patternsSkill
- feature-workflow-orchestratorSkill
- frontend-design-systemsSkill
- fullstack-starter-packSkill
- gcp-resource-optimizerSkill
- htmx-interaction-patternsSkill
- iterative-code-explorationSkill
- json-schema-designSkill
- mcp-builderSkill
- mcp-server-orchestratorSkill
- mobile-platform-architectSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 246
Always include: timestamp, level, event, service, request_id.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Error Handling & Logging Patterns
Build systems that are debuggable in production through structured logging and intentional error handling.
Error Hierarchy Design
Custom Exception Classes
class AppError(Exception):
"""Base error for the application."""
def __init__(self, message: str, code: str = "INTERNAL_ERROR", status: int = 500):
self.message = message
self.code = code
self.status = status
super().__init__(message)
class NotFoundError(AppError):
def __init__(self, entity: str, id: str):
super().__init__(f"{entity} '{id}' not found", code="NOT_FOUND", status=404)
class ValidationError(AppError):
def __init__(self, field: str, reason: str):
super().__init__(f"Invalid {field}: {reason}", code="VALIDATION_ERROR", status=400)
class ExternalServiceError(AppError):
def __init__(self, service: str, detail: str):
super().__init__(f"{service} error: {detail}", code="EXTERNAL_ERROR", status=502)Error Classification
| Category | Retry? | Log Level | Alert? |
| Validation error | No | WARNING | No |
| Not found | No | INFO | No |
| Auth failure | No | WARNING | Rate-based |
| Transient external | Yes | WARNING | After retries |
| Persistent external | No | ERROR | Yes |
| Internal bug | No | CRITICAL | Immediate |
Structured Logging
Setup with structlog
import structlog
import logging
def configure_logging(log_level: str = "INFO", json_output: bool = True):
processors = [
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
]
if json_output:
processors.append(structlog.processors.JSONRenderer())
else:
processors.append(structlog.dev.ConsoleRenderer())
structlog.configure(
processors=processors,
wrapper_class=structlog.make_filtering_bound_logger(
getattr(logging, log_level.upper())
),
context_class=dict,
logger_factory=structlog.PrintLoggerFactory(),
)
log = structlog.get_logger()Contextual Logging
import structlog
from contextvars import ContextVar
request_id_var: ContextVar[str] = ContextVar("request_id", default="")
# Bind context per request
structlog.contextvars.bind_contextvars(
request_id=request_id,
user_id=user.id,
organ="IV",
)
# All subsequent log calls include this context
log.info("processing_request", path="/api/skills", method="GET")
# Output: {"event": "processing_request", "request_id": "abc-123", "user_id": "u42", "path": "/api/skills", ...}Log Levels by Purpose
| Level | Purpose | Example |
| DEBUG | Detailed flow tracing | Query parameters, cache hits |
| INFO | Business events | User created, skill activated |
| WARNING | Recoverable issues | Retry attempt, deprecated usage |
| ERROR | Failures needing attention | External service down, data inconsistency |
| CRITICAL | System-level failures | Database unreachable, out of memory |
Request Middleware
FastAPI Correlation IDs
import uuid
from starlette.middleware.base import BaseHTTPMiddleware
class CorrelationMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
structlog.contextvars.bind_contextvars(request_id=request_id)
log.info("request_started",
method=request.method,
path=request.url.path,
)
try:
response = await call_next(request)
log.info("request_completed",
status=response.status_code,
)
response.headers["X-Request-ID"] = request_id
return response
except Exception as e:
log.error("request_failed", error=str(e), exc_info=True)
raise
finally:
structlog.contextvars.unbind_contextvars("request_id")Error Response Handler
from fastapi import Request
from fastapi.responses import JSONResponse
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
log.warning("app_error", code=exc.code, message=exc.message)
return JSONResponse(
status_code=exc.status,
content={"error": {"code": exc.code, "message": exc.message}},
)
@app.exception_handler(Exception)
async def unhandled_error_handler(request: Request, exc: Exception):
log.error("unhandled_error", error=str(exc), exc_info=True)
return JSONResponse(
status_code=500,
content={"error": {"code": "INTERNAL_ERROR", "message": "An unexpected error occurred"}},
)Logging Patterns
Operation Logging
async def process_skill(skill_id: str):
log.info("skill_processing_started", skill_id=skill_id)
try:
result = await validate_skill(skill_id)
log.info("skill_processing_completed", skill_id=skill_id, status=result.status)
return result
except ValidationError as e:
log.warning("skill_validation_failed", skill_id=skill_id, error=e.message)
raise
except Exception as e:
log.error("skill_processing_failed", skill_id=skill_id, error=str(e), exc_info=True)
raiseSensitive Data Filtering
SENSITIVE_KEYS = {"password", "token", "secret", "api_key", "authorization"}
def sanitize_log_data(data: dict) -> dict:
return {
k: "***REDACTED***" if k.lower() in SENSITIVE_KEYS else v
for k, v in data.items()
}Performance Logging
import time
from contextlib import contextmanager
@contextmanager
def log_duration(operation: str, **extra):
start = time.perf_counter()
try:
yield
finally:
duration_ms = (time.perf_counter() - start) * 1000
log.info(f"{operation}_duration", duration_ms=round(duration_ms, 2), **extra)Log Aggregation Integration
JSON Format for Ingestion
{
"timestamp": "2026-03-20T10:58:00Z",
"level": "info",
"event": "request_completed",
"request_id": "abc-123",
"method": "GET",
"path": "/api/skills",
"status": 200,
"duration_ms": 42.5,
"service": "a-i--skills",
"organ": "IV"
}Common Fields
Always include: timestamp, level, event, service, request_id. Optionally: user_id, organ, duration_ms, error.
Anti-Patterns
- Logging PII or secrets — Always filter sensitive fields before logging
- String interpolation in log calls — Use structured fields:
log.info("x", user=id)notlog.info(f"user {id}") - Catching and silencing exceptions — Log or re-raise; never
except: pass - Inconsistent log levels — Define team conventions and stick to them
- No correlation IDs — Impossible to trace requests across services without them
- Logging in tight loops — Rate-limit or sample high-frequency events
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

