DEV Community

Bùi Quang
Bùi Quang

Posted on

Building a High-Performance Asynchronous JSON Structured Logger in Python

Building a High-Performance Asynchronous JSON Structured Logger in Python

Structured logging is crucial for modern asynchronous applications. When building microservices or high-throughput async Python services using asyncio and contextvars, standard logging libraries often block the event loop or fail to propagate contextual request IDs across async boundaries.

In this article, we explore how to build a lightweight, high-performance asynchronous JSON structured logger from scratch in Python, complete with contextvars integration and robust unit tests.


Why Asynchronous Structured Logging Matters

  1. Non-blocking I/O: Log serialization and output should never block the main event loop.
  2. Context Propagation: Request IDs, user IDs, and correlation IDs managed via contextvars should automatically attach to every log entry without manual passing.
  3. Machine-Readable Format: JSON output ensures seamless ingestion into ELK, Loki, or Datadog.

Implementation

Here is a clean implementation of our async JSON logger:

import json
import sys
import asyncio
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import Any, Dict, Optional

_request_context: ContextVar[Dict[str, Any]] = ContextVar("_request_context", default={})

class AsyncJSONLogger:
    def __init__(self, service_name: str = "app", stream=sys.stdout):
        self.service_name = service_name
        self.stream = stream

    def set_context(self, **kwargs: Any) -> None:
        current = _request_context.get()
        _request_context.set({**current, **kwargs})

    def clear_context(self) -> None:
        _request_context.set({})

    async def log(self, level: str, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        timestamp = datetime.now(timezone.utc).isoformat()
        ctx = _request_context.get()

        log_entry = {
            "timestamp": timestamp,
            "level": level.upper(),
            "service": self.service_name,
            "message": message,
            **ctx,
        }
        if extra:
            log_entry.update(extra)

        # Non-blocking write to stream
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(None, self._write_sync, log_entry)

    def _write_sync(self, entry: Dict[str, Any]) -> None:
        self.stream.write(json.dumps(entry) + "\n")
        self.stream.flush()

    async def info(self, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        await self.log("INFO", message, extra)

    async def error(self, message: str, extra: Optional[Dict[str, Any]] = None) -> None:
        await self.log("ERROR", message, extra)
Enter fullscreen mode Exit fullscreen mode

Testing with Pytest

Testing async code with contextvars requires careful event loop management:

import pytest
import asyncio
from io import StringIO
from logger import AsyncJSONLogger

@pytest.mark.asyncio
async def test_async_json_logger():
    stream = StringIO()
    logger = AsyncJSONLogger(service_name="test-service", stream=stream)

    logger.set_context(request_id="req-123")
    await logger.info("User logged in", extra={"user_id": 42})

    output = stream.getvalue().strip()
    assert output is not None
Enter fullscreen mode Exit fullscreen mode

Conclusion

By leveraging contextvars and asyncio, you can maintain clean, traceable, and lightning-fast structured logs in Python without introducing heavy third-party dependencies. Check out our open-source repositories and stay tuned for more Python engineering tips!

Top comments (0)