Source code for structum_lab.logging.interfaces

# src/structum_lab/logging/interfaces.py
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: 2025 PythonWoods

"""Logging Interface Definition.

This module defines the `LoggerInterface` Protocol, which establishes the contract
for all loggers in the Structum ecosystem. This ensures that the core framework
and plugins can communicate logging intentions without depending on concrete
implementations (Dependency Inversion).
"""

from typing import Any, Protocol, runtime_checkable


[docs] @runtime_checkable class LoggerInterface(Protocol): """ Protocol for structured logging in Structum Lab. All logging implementations (stdlib adapter, structlog wrapper, custom loggers) must conform to this interface. It follows the standard Python logger API but explicitly supports ``**kwargs`` for structured contextual data. The protocol uses ``@runtime_checkable`` to enable ``isinstance()`` checks at runtime, useful for validation and debugging. Implementations: - :class:`~structum_lab.plugins.observability.logging.StructlogAdapter` - Standard library fallback (internal) Example: Basic logging with structured context:: from structum_lab.logging import get_logger log = get_logger(__name__) # Simple message log.info("Application started") # With structured data log.info("User logged in", user_id=123, ip="192.168.1.1") # Error with exception try: risky_operation() except Exception as e: log.error("Operation failed", exc_info=True, operation="risky") Note: All methods accept ``**kwargs`` for structured logging. Keys should be valid Python identifiers and values should be JSON-serializable. Structured data enables powerful log aggregation and analysis. See Also: :func:`~structum_lab.logging.get_logger`: Get a logger instance :func:`~structum_lab.logging.configure_logging`: Configure logging backend """
[docs] def debug(self, message: str, **kwargs: Any) -> None: """ Log a message at DEBUG level. Debug-level logs are typically used for detailed diagnostic information useful during development and troubleshooting. Args: message (str): The log message. **kwargs (Any): Structured context data (key-value pairs). Example: Debug logging with context:: log.debug("Cache lookup", key="user:123", hit=True, latency_ms=2.5) log.debug("SQL query", query="SELECT * FROM users", params={"id": 1}) Note: Debug logs are typically disabled in production for performance. """ ...
[docs] def info(self, message: str, **kwargs: Any) -> None: """ Log a message at INFO level. Info-level logs track general application flow and significant events (e.g., service started, configuration loaded, request completed). Args: message (str): The log message. **kwargs (Any): Structured context data (key-value pairs). Example: Info logging for application events:: log.info("Server started", host="0.0.0.0", port=8000) log.info("Request completed", path="/api/users", status=200, duration_ms=45) log.info("Database connected", driver="postgresql", pool_size=10) Note: This is the default log level for production environments. """ ...
[docs] def warning(self, message: str, **kwargs: Any) -> None: """ Log a message at WARNING level. Warning-level logs indicate potentially problematic situations that don't prevent the application from functioning but deserve attention. Args: message (str): The log message. **kwargs (Any): Structured context data (key-value pairs). Example: Warning logging for recoverable issues:: log.warning("Deprecated API used", endpoint="/old/api", caller="legacy_client") log.warning("High memory usage", usage_mb=1024, threshold_mb=800) log.warning("Retry attempt", operation="db_connect", attempt=2, max_attempts=3) Note: Warnings should be actionable - something that may need fixing but doesn't require immediate attention. """ ...
[docs] def error(self, message: str, **kwargs: Any) -> None: """ Log a message at ERROR level. Error-level logs indicate failures that prevent specific operations from completing but don't crash the application. Args: message (str): The log message. **kwargs (Any): Structured context data. Common keys: - ``exc_info`` (bool): Include exception traceback if True. - ``error_code`` (str): Application-specific error code. Example: Error logging with exception info:: try: process_payment(order_id) except PaymentError as e: log.error( "Payment processing failed", exc_info=True, order_id=order_id, error_code="PAYMENT_DECLINED" ) Warning: Errors indicate problems requiring investigation. Set up alerts for error rate thresholds in production. See Also: :meth:`critical`: For application-critical failures """ ...
[docs] def critical(self, message: str, **kwargs: Any) -> None: """ Log a message at CRITICAL level. Critical-level logs indicate severe errors that may cause the application to abort or enter an unstable state. Args: message (str): The log message. **kwargs (Any): Structured context data (key-value pairs). Example: Critical logging for fatal errors:: log.critical( "Database connection pool exhausted", active_connections=100, max_connections=100, pending_requests=50 ) log.critical( "Configuration file corrupted", path="/etc/app/config.toml", exc_info=True ) Warning: Critical logs should trigger immediate alerts. These indicate situations where the application cannot continue safely. Note: After logging a critical message, the application may need to shut down gracefully or enter a safe degraded mode. """ ...