Logger Configuration API¶
Configuration classes, presets, and utilities for the logger module.
Main Configuration¶
LoggerConfig¶
LoggerConfig
¶
Bases: BaseModel
Logger instance configuration.
Source code in src/jinpy_utils/logger/config.py
GlobalLoggerConfig¶
GlobalLoggerConfig
¶
Bases: BaseModel
Global logger configuration following 12-factor app principles.
Source code in src/jinpy_utils/logger/config.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | |
Backend Configurations¶
BackendConfig¶
BackendConfig
¶
Bases: BaseModel
Base configuration for logging backends.
Source code in src/jinpy_utils/logger/config.py
ConsoleBackendConfig¶
ConsoleBackendConfig
¶
Bases: BackendConfig
Configuration for console logging backend.
Source code in src/jinpy_utils/logger/config.py
FileBackendConfig¶
FileBackendConfig
¶
Bases: BackendConfig
Configuration for file logging backend.
Source code in src/jinpy_utils/logger/config.py
RestApiBackendConfig¶
RestApiBackendConfig
¶
Bases: BackendConfig
Configuration for REST API logging backend.
Source code in src/jinpy_utils/logger/config.py
WebSocketBackendConfig¶
WebSocketBackendConfig
¶
Bases: BackendConfig
Configuration for WebSocket logging backend.
Source code in src/jinpy_utils/logger/config.py
DatabaseBackendConfig¶
DatabaseBackendConfig
¶
Bases: BackendConfig
Configuration for database logging backend.
Source code in src/jinpy_utils/logger/config.py
RetryConfig¶
RetryConfig
¶
Bases: BaseModel
Retry configuration for backend operations.
Source code in src/jinpy_utils/logger/config.py
SecurityConfig¶
SecurityConfig
¶
Bases: BaseModel
Security configuration for logger backends.
Source code in src/jinpy_utils/logger/config.py
Configuration Presets¶
create_development_config¶
create_development_config
¶
create_development_config() -> GlobalLoggerConfig
Create development environment configuration.
Source code in src/jinpy_utils/logger/config.py
create_production_config¶
create_production_config
¶
create_production_config() -> GlobalLoggerConfig
Create production environment configuration.
Source code in src/jinpy_utils/logger/config.py
create_cloud_config¶
create_cloud_config
¶
create_cloud_config(api_url: str, api_key: str) -> GlobalLoggerConfig
Create cloud logging configuration.
Source code in src/jinpy_utils/logger/config.py
Enums and Constants¶
LogLevel¶
LogLevel
¶
Bases: str, Enum
Log level enumeration with string values.
Source code in src/jinpy_utils/logger/enums.py
LogFormat¶
LogFormat
¶
Bases: str, Enum
Log output format options.
Source code in src/jinpy_utils/logger/enums.py
BackendType¶
BackendType
¶
Bases: str, Enum
Supported logging backend types.
Source code in src/jinpy_utils/logger/enums.py
BatchStrategy¶
BatchStrategy
¶
CompressionType¶
CompressionType
¶
ConnectionState¶
ConnectionState
¶
Bases: str, Enum
Connection states for backends.
Source code in src/jinpy_utils/logger/enums.py
RetryStrategy¶
RetryStrategy
¶
SecurityLevel¶
SecurityLevel
¶
Bases: str, Enum
Security levels for logging operations.
Source code in src/jinpy_utils/logger/enums.py
Examples¶
Basic Configuration¶
from jinpy_utils.logger import LoggerConfig, ConsoleBackendConfig, LogLevel
config = LoggerConfig(
level=LogLevel.INFO,
backends=[
ConsoleBackendConfig(
level=LogLevel.DEBUG,
use_colors=True
)
]
)
File Logging Configuration¶
from jinpy_utils.logger import LoggerConfig, FileBackendConfig, LogLevel, LogFormat
config = LoggerConfig(
level=LogLevel.DEBUG,
backends=[
FileBackendConfig(
level=LogLevel.INFO,
file_path="logs/app.log",
format=LogFormat.JSON,
max_size_mb=50,
backup_count=10,
compression=True
)
]
)
Multiple Backend Configuration¶
from jinpy_utils.logger import (
LoggerConfig,
ConsoleBackendConfig,
FileBackendConfig,
RestApiBackendConfig,
LogLevel
)
config = LoggerConfig(
level=LogLevel.DEBUG,
async_enabled=True,
backends=[
ConsoleBackendConfig(
level=LogLevel.DEBUG,
use_colors=True
),
FileBackendConfig(
level=LogLevel.INFO,
file_path="logs/app.log",
max_size_mb=100,
backup_count=5
),
RestApiBackendConfig(
level=LogLevel.ERROR,
endpoint="https://logs.example.com/api/logs",
batch_size=50
)
]
)
Environment-Based Configuration¶
import os
from jinpy_utils.logger import LoggerConfig, create_development_config, create_production_config
def get_config() -> LoggerConfig:
"""Get configuration based on environment."""
env = os.environ.get("ENVIRONMENT", "development")
if env == "production":
return create_production_config()
elif env == "staging":
return create_production_config(level=LogLevel.DEBUG)
else:
return create_development_config()
config = get_config()
Configuration Validation¶
from jinpy_utils.logger import LoggerConfig, ConsoleBackendConfig
from jinpy_utils.base import JPYConfigurationError
try:
config = LoggerConfig(
level=LogLevel.INFO,
backends=[
ConsoleBackendConfig(
level=LogLevel.DEBUG
)
]
)
config.validate()
except JPYConfigurationError as e:
print(f"Configuration error: {e.message}")
Dynamic Configuration Updates¶
from jinpy_utils.logger import get_logger, LoggerConfig, FileBackendConfig
logger = get_logger("app")
# Add a new backend at runtime
file_backend = FileBackendConfig(
level=LogLevel.WARNING,
file_path="warnings.log"
)
logger.add_backend(file_backend)
Configuration Serialization¶
from jinpy_utils.logger import LoggerConfig, ConsoleBackendConfig
import json
# Create configuration
config = LoggerConfig(
level=LogLevel.INFO,
backends=[ConsoleBackendConfig(level=LogLevel.DEBUG)]
)
# Serialize to dictionary
config_dict = config.to_dict()
# Save to JSON file
with open("logger_config.json", "w") as f:
json.dump(config_dict, f, indent=2)
# Load from JSON file
with open("logger_config.json", "r") as f:
loaded_dict = json.load(f)
# Recreate configuration
loaded_config = LoggerConfig.from_dict(loaded_dict)
Advanced REST API Configuration¶
from jinpy_utils.logger import LoggerConfig, RestApiBackendConfig, RetryConfig, SecurityConfig
config = LoggerConfig(
backends=[
RestApiBackendConfig(
level=LogLevel.INFO,
endpoint="https://logs.example.com/api/v1/logs",
headers={
"Authorization": "Bearer YOUR_TOKEN",
"Content-Type": "application/json",
"X-Source": "jinpy-utils"
},
timeout_seconds=30,
retry_config=RetryConfig(
max_attempts=5,
backoff_factor=2.0,
backoff_strategy=RetryStrategy.EXPONENTIAL
),
security_config=SecurityConfig(
encrypt_payload=True,
verify_ssl=True,
security_level=SecurityLevel.HIGH
),
batch_size=100,
batch_timeout=10.0,
max_queue_size=10000
)
]
)
Cloud-Optimized Configuration¶
from jinpy_utils.logger import create_cloud_config
import os
config = create_cloud_config(
service_name=os.environ.get("SERVICE_NAME", "my-service"),
environment=os.environ.get("ENVIRONMENT", "production"),
version=os.environ.get("SERVICE_VERSION", "1.0.0"),
cloud_provider=os.environ.get("CLOUD_PROVIDER", "aws"), # aws, gcp, azure
region=os.environ.get("AWS_REGION", "us-east-1")
)
WebSocket Configuration with Reconnection¶
from jinpy_utils.logger import LoggerConfig, WebSocketBackendConfig
config = LoggerConfig(
backends=[
WebSocketBackendConfig(
level=LogLevel.INFO,
endpoint="wss://logs.example.com/ws",
headers={
"Authorization": "Bearer YOUR_TOKEN"
},
reconnect_interval=5.0,
max_reconnect_attempts=10,
ping_interval=30.0,
ping_timeout=10.0,
compression=True
)
]
)
Configuration Best Practices¶
Environment Variables¶
import os
from jinpy_utils.logger import LoggerConfig, FileBackendConfig, LogLevel
def create_config_from_env() -> LoggerConfig:
"""Create configuration from environment variables."""
return LoggerConfig(
level=LogLevel[os.environ.get("LOG_LEVEL", "INFO")],
async_enabled=os.environ.get("LOG_ASYNC", "true").lower() == "true",
backends=[
FileBackendConfig(
file_path=os.environ.get("LOG_FILE", "app.log"),
max_size_mb=int(os.environ.get("LOG_MAX_SIZE_MB", "100")),
backup_count=int(os.environ.get("LOG_BACKUP_COUNT", "5"))
)
]
)
Configuration Hierarchy¶
from pathlib import Path
import yaml
from jinpy_utils.logger import LoggerConfig
def load_hierarchical_config() -> LoggerConfig:
"""Load configuration with hierarchy."""
config_sources = [
Path("/etc/myapp/logging.yaml"), # System config
Path.home() / ".myapp" / "logging.yaml", # User config
Path("logging.yaml"), # Local config
]
merged_config = {}
for config_file in config_sources:
if config_file.exists():
with open(config_file) as f:
config = yaml.safe_load(f)
merged_config.update(config)
return LoggerConfig.from_dict(merged_config.get("logger", {}))
Configuration Validation¶
from jinpy_utils.logger import LoggerConfig
from jinpy_utils.base import JPYConfigurationError
def validate_production_config(config: LoggerConfig) -> None:
"""Validate configuration for production use."""
if config.level.value < LogLevel.INFO.value:
raise JPYConfigurationError(
message="Production logging level should be INFO or higher",
config_key="level",
suggestions=["Set level to INFO, WARNING, or ERROR"]
)
if not config.async_enabled:
raise JPYConfigurationError(
message="Async logging should be enabled in production",
config_key="async_enabled",
suggestions=["Set async_enabled to True for better performance"]
)
Testing Configuration¶
from jinpy_utils.logger import LoggerConfig, ConsoleBackendConfig, LogLevel
def create_test_config() -> LoggerConfig:
"""Create configuration optimized for testing."""
return LoggerConfig(
level=LogLevel.WARNING, # Reduce noise in tests
async_enabled=False, # Synchronous for predictable testing
backends=[
ConsoleBackendConfig(
level=LogLevel.WARNING,
use_colors=False, # No colors in test output
show_source=False # Cleaner test output
)
]
)