Files
PecHub/backend/app/core/logging.py
T
mgiustini 58a233236c feat: Fase 1 – Fondamenta complete (backend FastAPI + auth + permessi)
- docker-compose.yml: PostgreSQL 16, Redis 7, MinIO, Nginx
- backend FastAPI: struttura monorepo, config pydantic-settings
- modelli SQLAlchemy: tutti i modelli (tenants, users, mailboxes, messages, archival, permissions, labels, audit_log)
- migrazione Alembic 0001: schema completo in pure SQL
- auth API: login JWT, refresh token rotation, logout, 2FA TOTP (setup/verify/disable)
- CRUD utenti: lista, crea, modifica, reset password, soft delete
- permessi granulari (Fase 1-A): mailbox_permissions, assegna/revoca/lista
- CRUD tenant: gestione super-admin
- sicurezza: AES-256-GCM cifratura credenziali IMAP/SMTP, bcrypt password
- RLS PostgreSQL: isolamento multi-tenant per request
- seed sviluppo: tenant demo + admin + operator
- test unit: security (bcrypt, JWT, AES), auth_service
- test integration: auth endpoints, users endpoints
- CI GitHub Actions: lint (ruff), test (pytest), build Docker, security scan
- infra: nginx.conf, redis.conf
- Makefile con comandi make dev/test/migrate/seed

Definition of Done:
 Login, refresh token e TOTP funzionanti
 make dev porta in piedi tutto lo stack locale
 CI configurata
2026-03-18 16:42:01 +01:00

66 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Structured logging per PecFlow.
In produzione (LOG_JSON=true) emette log JSON per aggregatori (Loki, ELK).
In sviluppo emette log leggibili colorati.
"""
import logging
import sys
from typing import Any
from app.config import get_settings
settings = get_settings()
def _build_handler() -> logging.Handler:
handler = logging.StreamHandler(sys.stdout)
if settings.log_json:
try:
import json
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
log_entry: dict[str, Any] = {
"timestamp": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
if record.exc_info:
log_entry["exception"] = self.formatException(record.exc_info)
return json.dumps(log_entry, ensure_ascii=False)
handler.setFormatter(JsonFormatter())
except Exception:
pass
else:
fmt = "%(asctime)s %(levelname)-8s %(name)s %(message)s"
handler.setFormatter(logging.Formatter(fmt, datefmt="%H:%M:%S"))
return handler
def setup_logging() -> None:
"""Configura il logging applicativo. Da chiamare all'avvio dell'app."""
level = getattr(logging, settings.log_level.upper(), logging.INFO)
root_logger = logging.getLogger()
root_logger.setLevel(level)
# Rimuovi handler esistenti per evitare duplicati
root_logger.handlers.clear()
root_logger.addHandler(_build_handler())
# Riduci verbosità librerie rumorose
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.engine").setLevel(
logging.INFO if settings.app_debug else logging.WARNING
)
def get_logger(name: str) -> logging.Logger:
"""Restituisce un logger con il nome specificato."""
return logging.getLogger(name)