Skip to content
This repository has been archived by the owner on Sep 12, 2023. It is now read-only.

Commit

Permalink
fix: msgspec json log rendering
Browse files Browse the repository at this point in the history
Adds a custom rendering processor to the processor chain that uses
msgspec encoder.

Closes #166
  • Loading branch information
peterschutt committed Dec 14, 2022
1 parent 2a439e7 commit 818539d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
14 changes: 5 additions & 9 deletions src/starlite_saqlalchemy/log/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
import logging
from typing import TYPE_CHECKING

import msgspec
import structlog
from starlite.config.logging import LoggingConfig

from starlite_saqlalchemy import settings

from . import controller, worker
from .msgspec_renderer import msgspec_json_renderer

if TYPE_CHECKING:
from collections.abc import Sequence
Expand All @@ -27,24 +27,20 @@
"worker",
)


default_processors = [
structlog.contextvars.merge_contextvars,
controller.drop_health_logs,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", utc=True),
]

if settings.app.ENVIRONMENT == "local":
if settings.app.ENVIRONMENT == "local": # pragma: no cover
LoggerFactory: Any = structlog.WriteLoggerFactory
default_processors.extend([structlog.dev.ConsoleRenderer()])
else: # pragma: no cover
else:
LoggerFactory = structlog.BytesLoggerFactory
default_processors.extend(
[
structlog.processors.dict_tracebacks,
structlog.processors.JSONRenderer(serializer=msgspec.json.encode),
]
)
default_processors.extend([structlog.processors.dict_tracebacks, msgspec_json_renderer])


def configure(processors: Sequence[Processor]) -> None:
Expand Down
31 changes: 31 additions & 0 deletions src/starlite_saqlalchemy/log/msgspec_renderer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""A JSON Renderer for structlog using msgspec.
Msgspec doesn't have an API consistent with the stdlib's `json` module,
which is required for structlog's `JSONRenderer`.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import msgspec

if TYPE_CHECKING:
from structlog.typing import EventDict, WrappedLogger


_encoder = msgspec.json.Encoder()


def msgspec_json_renderer(_: WrappedLogger, __: str, event_dict: EventDict) -> bytes:
"""Structlog processor that uses `msgspec` for JSON encoding.
Args:
_ ():
__ ():
event_dict (): The data to be logged.
Returns:
The log event encoded to JSON by msgspec.
"""
return _encoder.encode(event_dict)

0 comments on commit 818539d

Please sign in to comment.