Implementing Structured Logging with Loguru in Python

Getting Started with Loguru

To begin using Loguru, install it via pip:

pip install loguru

Basic Usage Example

Loguru simplifies logging with its pre-configured logger:

from loguru import logger

logger.info('Application initialized')

The default output format includes timestamp, log level, module information, and colored output:

2023-08-15 14:30:45.123 | INFO     | __main__:<module>:3 - Application initialized

File Output Configuration

To save logs to a file:

logger.add('app_logs.log')
logger.warning('Potential issue detected')

Advanced Configuration Options

Log Rotation

Configure log rotation based on size or time:

# Rotate when file reaches 100MB
logger.add('app_{time}.log', rotation='100 MB')

# Daily rotation at midnight
logger.add('daily_logs.log', rotation='00:00')

Log Retention

Automatically clean old log files:

# Keep logs for 7 days
logger.add('system.log', retention='7 days')

Comprestion

Compress archived logs:

logger.add('archive.log', compression='zip')

Enhanced Logging Features

Structured Formatting

Use Python's string formatting in logs:

logger.debug('User {user_id} logged in from {ip}', 
             user_id=42, ip='192.168.1.1')

Error Tracing

Automatically capture exceptions with context:

@logger.catch
def process_data(data):
    return sum(int(x) for x in data)

Intercept Standard Logging

Route traditional logging to Loguru:

class LoguruHandler(logging.Handler):
    def emit(self, record):
        logger_ctx = logger.opt(depth=6, exception=record.exc_info)
        logger_ctx.log(record.levelno, record.getMessage())

logging.basicConfig(handlers=[LoguruHandler()], level=logging.INFO)

Tags: python Loguru logging structured-logging error-handling

Posted on Sun, 27 Sep 2026 16:06:32 +0000 by ScubaDvr2