Skip to content

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.

python
from pyptp.ptp_log import logger

# This produces no output (silent by default)
logger.info("Nothing happens")

Enabling Logging

Basic Console Logging

python
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

LevelValueUse Case
TRACE5Finest-grained diagnostic info
DEBUG10Detailed development diagnostics
INFO20General operational messages
SUCCESS25Successful operation completion
WARNING30Potential issues that don't stop execution
ERROR40Errors affecting specific operations
CRITICAL50System-wide failures
python
# 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

python
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:

python
configure_logging(level="INFO", sink="pyptp.log", colorize=False)

Multiple Destinations

Log to both console and file simultaneously:

python
# 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:

python
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

python
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 loaded

Format Placeholders

PlaceholderDescription
{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

python
# 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

python
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):

python
# 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

python
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

python
# Verbose console output with colors
configure_logging(level="DEBUG", colorize=True)

Production Setup

python
# File logging, minimal console output
configure_logging(level="WARNING", colorize=False)  # Console
configure_logging(level="INFO", sink="/var/log/pyptp.log", colorize=False)  # File

Testing Setup

python
# 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_output

Complete Example

python
"""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