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.
Python code
37 linesimport 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
{"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
- Use the actual loguru library if available and just patch `sys.stdout` to capture its output
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.