Skip to content

Closes #170: Errorhandling and structured logging#236

Closed
KodeSage wants to merge 1 commit intoSolFoundry:mainfrom
KodeSage:feat/error_handling_structured_logging
Closed

Closes #170: Errorhandling and structured logging#236
KodeSage wants to merge 1 commit intoSolFoundry:mainfrom
KodeSage:feat/error_handling_structured_logging

Conversation

@KodeSage
Copy link
Contributor

Description

Closes #170

Implements centralized error handling and structured logging across the entire SolFoundry backend. Every API error, webhook event, and payout action is now traceable via correlation IDs and structured JSON logs.

What's included:

Core Infrastructure (backend/app/core/)

  • logging_config.py — Structured JSON logging with 4 separate log streams (application, access, error, audit), rotating file handlers, and configurable retention policy
  • correlation.py — Correlation ID middleware that assigns/propagates X-Correlation-ID headers via contextvars for distributed request tracing
  • exceptions.py — Global exception handlers for HTTPException, RequestValidationError, and unhandled exceptions — all return structured JSON responses with {error: {code, message, correlation_id, details}}
  • audit.py — Dedicated audit logger for sensitive operations (payouts, auth, bounty state changes, webhooks)

Enhanced Health Check

  • /health endpoint now reports dependency status for Database and Redis with healthy/degraded/unhealthy states

Audit Trail Coverage

  • Auth: GitHub login, wallet login, wallet linking, token refresh
  • Payouts: payout creation, buyback creation
  • Bounties: create, update, delete, cancel
  • Webhooks: pull_request and issues events

Configuration (all via environment variables)

  • LOG_DIR — log output directory (default: logs/)
  • LOG_LEVEL — root log level (default: INFO)
  • LOG_FORMATjson or text (default: json)
  • LOG_MAX_BYTES — rotation size per file (default: 10MB)
  • LOG_BACKUP_COUNT — rotated file count (default: 5)
  • LOG_RETENTION_DAYS — retention policy (default: 30 days)

Tests — 40 new tests (unit + integration)

  • test_error_handling.py (8) — structured error responses
  • test_correlation.py (6) — correlation ID middleware
  • test_logging_config.py (8) — JSON/text formatters, filters, setup
  • test_audit.py (5) — audit event emission
  • test_health_check.py (7) — enhanced health endpoint
  • test_middleware_integration.py (6) — end-to-end pipeline

Solana Wallet for Payout

Wallet: EwWiRi5zkynTYN9pvgjqCEiWKuFwR7SLdgFox9R3GmyS

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update
  • 🎨 Style/UI update
  • ♻️ Code refactoring
  • ⚡ Performance improvement
  • ✅ Test addition/update

Checklist

  • Code is clean and follows the issue spec exactly
  • One PR per bounty (no multiple bounties in one PR)
  • Tests included for new functionality
  • All existing tests pass
  • No console.log or debugging code left behind
  • No hardcoded secrets or API keys

Testing

  • Manual testing performed
  • Unit tests added/updated
  • Integration tests added/updated

All 40 new tests pass. All 129 existing bounty tests pass with zero regressions. Pre-existing test_payouts.py::TestValidation::test_invalid_wallet (previously broken by non-serializable ValueError in validation errors) now also passes thanks to the _sanitize_errors fix in the global exception handler.

tests/test_error_handling.py       8 passed
tests/test_correlation.py          6 passed
tests/test_logging_config.py       8 passed
tests/test_audit.py                5 passed
tests/test_health_check.py         7 passed
tests/test_middleware_integration.py 6 passed
======================== 40 passed, 0 failed =================

Structured JSON error response (404):

{
  "error": {
    "code": 404,
    "message": "Bounty not found",
    "correlation_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
  }
}

Structured JSON audit log entry:

{
  "timestamp": "2026-03-21T00:10:35.498544+00:00",
  "level": "INFO",
  "logger": "solfoundry.audit",
  "message": "AUDIT payout.created payout/tx-abc123 by user=user-42",
  "correlation_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "action": "payout.created",
  "resource_type": "payout",
  "resource_id": "tx-abc123",
  "user_id": "user-42",
  "details": {"recipient": "alice", "amount": 1000, "token": "FNDRY"}
}

Enhanced health check response:

{
  "status": "healthy",
  "bounties": 42,
  "contributors": 15,
  "last_sync": "2026-03-21T00:05:00+00:00",
  "dependencies": {
    "database": {"status": "healthy"},
    "redis": {"status": "healthy"}
  }
}

Additional Notes

  • All new code is Python 3.9+ compatible (uses from __future__ import annotations and typing.Optional instead of X | None syntax)
  • Fixed a pre-existing Python 3.9 incompatibility in backend/app/api/webhooks/github.py (str | NoneOptional[str])
  • Log streams use propagate = False for access and audit loggers to prevent duplicate entries in the root logger
  • The _sanitize_errors utility in the exception handler converts non-JSON-serializable objects (like ValueError instances in Pydantic validation contexts) to strings, fixing a latent bug
  • No new dependencies required — uses only Python stdlib (logging, logging.handlers, contextvars, uuid, json)

@chronoeth-creator, this is completed!

@KodeSage KodeSage closed this Mar 21, 2026
Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: APPROVED

@coderabbitai
Copy link

coderabbitai bot commented Mar 21, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This pull request implements centralized error handling and structured logging infrastructure for the backend. It introduces audit logging calls to authentication, bounty, and payout endpoints; creates new core modules for audit trail tracking, correlation ID propagation, exception handling, and logging configuration; updates the health check endpoint to include service dependency status; and adds comprehensive test coverage for all new components. The changes are integrated into the main application via middleware registration and exception handler setup.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

approved, paid

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Closes #170: Errorhandling and structured logging' clearly and specifically describes the main feature: implementing centralized error handling and structured logging as per issue #170.
Description check ✅ Passed The PR description thoroughly documents the implementation, covering all core infrastructure components, API enhancements, audit trail coverage, configuration options, and comprehensive test results with examples.
Linked Issues check ✅ Passed All requirements from issue #170 are implemented: global exception handler middleware [exceptions.py], structured logging with correlation IDs [logging_config.py, correlation.py], all log levels supported, four separate log streams (application/access/error/audit), audit logging for sensitive operations [audit.py], log rotation configured, and enhanced health endpoint with dependency status.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #170 requirements. The .gitignore addition (logs/) and GitHub webhook type annotation updates (str|None→Optional[str] for Python 3.9 compatibility) are supportive scope extensions, not out-of-scope changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link

⚠️ Auto-rejected by review pipeline

Reason: PR description is empty or too short (< 20 chars)

If you believe this is an error, please fix and reopen.


SolFoundry Review Bot

@github-actions github-actions bot closed this Mar 21, 2026
@KodeSage KodeSage deleted the feat/error_handling_structured_logging branch March 22, 2026 11:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant