Logging Configuration
This guide covers PyPtP's logging system built on Loguru. Learn how to enable logging, configure output destinations, customize formats, and set up multiple handlers.
Full Example
View the complete code: 06_logging.py
Silent by Default
PyPtP follows Python library best practices: no logging output is produced until explicitly enabled. This prevents unexpected console spam when PyPtP is used as a dependency in larger applications.
from pyptp.ptp_log import logger
# This produces no output (silent by default)
logger.info("Nothing happens")Enabling Logging
Basic Console Logging
from pyptp import NetworkLV
from pyptp.ptp_log import configure_logging, logger
# Enable INFO level to console
configure_logging(level="INFO")
network = NetworkLV()
logger.info("Created network: {}", network)Log Levels
| Level | Value | Use Case |
|---|---|---|
TRACE | 5 | Finest-grained diagnostic info |
DEBUG | 10 | Detailed development diagnostics |
INFO | 20 | General operational messages |
SUCCESS | 25 | Successful operation completion |
WARNING | 30 | Potential issues that don't stop execution |
ERROR | 40 | Errors affecting specific operations |
CRITICAL | 50 | System-wide failures |
# Enable DEBUG for troubleshooting
configure_logging(level="DEBUG", colorize=True)
logger.debug("This is debug information")
logger.info("This is info")
logger.warning("This is a warning")Output Destinations
File Logging
from pathlib import Path
log_file = Path("pyptp.log")
configure_logging(level="INFO", sink=log_file)When logging to files, disable colorization for cleaner output:
configure_logging(level="INFO", sink="pyptp.log", colorize=False)Multiple Destinations
Log to both console and file simultaneously:
# Console with colors
configure_logging(level="INFO", colorize=True)
# File with verbose output
configure_logging(level="DEBUG", sink="debug.log", colorize=False)Custom Sinks
Loguru supports various sink types:
import sys
# Standard error (default)
configure_logging(sink=sys.stderr)
# Standard output
configure_logging(sink=sys.stdout)
# Custom function
def custom_sink(message):
# Send to external service, database, etc.
print(f"CUSTOM: {message}")
configure_logging(sink=custom_sink)Format Customization
Custom Format String
configure_logging(
level="INFO",
format_string="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
)Default Format
The default format includes timestamp, level, location, and message:
2025-01-15 14:30:45 | INFO | pyptp.network:load:123 - Network loadedFormat Placeholders
| Placeholder | Description |
|---|---|
{time} | Timestamp (customizable format) |
{level} | Log level name |
{name} | Logger name (module path) |
{function} | Function name |
{line} | Line number |
{message} | The log message |
{extra} | Additional bound context |
Timestamp Formats
# ISO 8601
format_string="{time:YYYY-MM-DDTHH:mm:ss.SSSZ} | {message}"
# Date only
format_string="{time:YYYY-MM-DD} | {message}"
# Time only
format_string="{time:HH:mm:ss} | {message}"Using the Logger
Basic Logging
from pyptp.ptp_log import logger
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")Formatted Messages
PyPtP uses Loguru's bracket-style formatting (similar to Python's str.format):
# Positional arguments
logger.info("Loaded {} nodes and {} cables", node_count, cable_count)
# Named arguments
logger.info("Node {name} at {voltage}kV", name="Sub1", voltage=10.0)Exception Logging
try:
network = NetworkMV.from_file("missing.vnf")
except Exception:
logger.exception("Failed to load network")The exception() method automatically includes the stack trace.
Configuration Patterns
Development Setup
# Verbose console output with colors
configure_logging(level="DEBUG", colorize=True)Production Setup
# File logging, minimal console output
configure_logging(level="WARNING", colorize=False) # Console
configure_logging(level="INFO", sink="/var/log/pyptp.log", colorize=False) # FileTesting Setup
# Capture logs for assertions
import io
log_capture = io.StringIO()
configure_logging(level="DEBUG", sink=log_capture, colorize=False)
# Run code that logs...
log_output = log_capture.getvalue()
assert "expected message" in log_outputComplete Example
"""Logging Configuration Examples.
Shows how to configure PyPtP logging for different use cases.
"""
from pathlib import Path
from pyptp import NetworkLV
from pyptp.ptp_log import configure_logging, logger
# Example 1: Enable console logging at INFO level
configure_logging(level="INFO")
network = NetworkLV()
logger.info("Created network: {}", network)
# Example 2: Enable DEBUG logging for troubleshooting
configure_logging(level="DEBUG", colorize=True)
logger.debug("This is debug information")
logger.info("This is info")
logger.warning("This is a warning")
# Example 3: Log to file
log_file = Path("pyptp.log")
configure_logging(level="INFO", sink=log_file)
# Example 4: Custom format
configure_logging(
level="INFO",
format_string="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
)
# Example 5: Multiple sinks (console + file)
configure_logging(level="INFO", colorize=True)
configure_logging(level="DEBUG", sink="debug.log", colorize=False)
# Note: PyPtP is silent by default - no logging unless configured