Mocking loguru for Structured Logging in Python

Simulate loguru's structured logging with a custom mock that captures JSON-formatted log entries with bound context.

Medium Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Python code

37 lines
Python 3.9+
import json
import sys
from io import StringIO
from unittest.mock import patch


def mock_loguru():
    # Simulate a structured logger with context binding
    class StructuredLogger:
        def __init__(self):
            self.context = {}

        def bind(self, **kwargs):
            logger = StructuredLogger()
            logger.context = {**self.context, **kwargs}
            return logger

        def info(self, message, **kwargs):
            log_entry = {"level": "INFO", "message": message, "context": self.context}
            log_entry.update(kwargs)
            print(json.dumps(log_entry))

    return StructuredLogger()


if __name__ == "__main__":
    # Test the mocked structured logger
    captured_output = StringIO()
    with patch("sys.stdout", captured_output):
        logger = mock_loguru()
        session_logger = logger.bind(user_id=42, session="abc123")
        session_logger.info("User logged in", event="login")

        root_logger = mock_loguru()
        root_logger.info("Server started", port=8080)

    print(captured_output.getvalue().strip())

Output

stdout
{"level": "INFO", "message": "User logged in", "context": {"user_id": 42, "session": "abc123"}, "event": "login"}
{"level": "INFO", "message": "Server started", "context": {}, "port": 8080}

How it works

The mock_loguru function returns a StructuredLogger class that mimics loguru's API, including a bind method that returns a new logger with merged context. The info method builds a JSON object with level, message, context, and any extra keyword arguments, then prints it as a JSON string. The test uses patch("sys.stdout") to capture the output, demonstrating the JSON format. This pattern helps simulate structured logging without external dependencies, useful for unit tests or quick prototypes.

Common mistakes

  • Forgetting to include `context` in the log entry when binding is used
  • Not resetting context between different logger instances, causing stale data
  • Assuming `bind` mutates the original logger instead of returning a new one

Variations

  1. Use the actual loguru library if available and just patch `sys.stdout` to capture its output
  2. Extend the mock to support additional log levels like `warning` or `error` with different severity prefixes

Real-world use cases

  • Unit testing applications that use structured logging without installing loguru as a dependency.
  • Prototyping log formats and context binding behavior before integrating a logging framework.
  • Capturing and asserting JSON log output in integration tests to verify context enrichment.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.