Skip to content

Commit a1cb869

Browse files
committed
Added external logging
1 parent 6df6c75 commit a1cb869

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

microbootstrap/instruments/logging_instrument.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from __future__ import annotations
1+
from future import annotations
22
import logging
33
import logging.handlers
44
import time
@@ -71,18 +71,29 @@ def tracer_injection(_: WrappedLogger, __: str, event_dict: EventDict) -> EventD
7171
return event_dict
7272

7373

74-
DEFAULT_STRUCTLOG_PROCESSORS: typing.Final[list[typing.Any]] = [
75-
structlog.stdlib.filter_by_level,
76-
structlog.stdlib.add_log_level,
74+
DEFAULT_STRUCTLOG_PRE_CHAIN_PROCESSORS: typing.Final[list[typing.Any]] = [
7775
structlog.stdlib.add_logger_name,
78-
tracer_injection,
76+
structlog.stdlib.add_log_level,
7977
structlog.stdlib.PositionalArgumentsFormatter(),
8078
structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
8179
structlog.processors.StackInfoRenderer(),
8280
structlog.processors.format_exc_info,
81+
]
82+
DEFAULT_STRUCTLOG_PROCESSORS: typing.Final[list[typing.Any]] = [
83+
*DEFAULT_STRUCTLOG_PRE_CHAIN_PROCESSORS,
84+
structlog.stdlib.filter_by_level,
85+
tracer_injection,
8386
structlog.processors.UnicodeDecoder(),
8487
]
85-
DEFAULT_STRUCTLOG_FORMATTER_PROCESSOR: typing.Final = structlog.processors.JSONRenderer(serializer=orjson.dumps)
88+
89+
90+
def _serialize_log_with_orjson_to_string(value: typing.Any, **kwargs: typing.Any) -> str: # noqa: ANN401
91+
return orjson.dumps(value, **kwargs).decode()
92+
93+
94+
DEFAULT_STRUCTLOG_FORMATTER_PROCESSOR: typing.Final = structlog.processors.JSONRenderer(
95+
serializer=_serialize_log_with_orjson_to_string
96+
)
8697

8798

8899
class MemoryLoggerFactory(structlog.stdlib.LoggerFactory):
@@ -150,6 +161,8 @@ def bootstrap(self) -> None:
150161
for unset_handlers_logger in self.instrument_config.logging_unset_handlers:
151162
logging.getLogger(unset_handlers_logger).handlers = []
152163

164+
stream_handler: typing.Final = logging.StreamHandler()
165+
root_logger: typing.Final = logging.getLogger()
153166
structlog.configure(
154167
processors=[
155168
*DEFAULT_STRUCTLOG_PROCESSORS,
@@ -165,6 +178,17 @@ def bootstrap(self) -> None:
165178
wrapper_class=structlog.stdlib.BoundLogger,
166179
cache_logger_on_first_use=True,
167180
)
181+
stream_handler.setFormatter(
182+
structlog.stdlib.ProcessorFormatter(
183+
foreign_pre_chain=[
184+
*DEFAULT_STRUCTLOG_PRE_CHAIN_PROCESSORS,
185+
structlog.stdlib.ProcessorFormatter.remove_processors_meta,
186+
],
187+
processors=[structlog.processors.JSONRenderer()],
188+
logger=root_logger,
189+
)
190+
)
191+
root_logger.addHandler(stream_handler)
168192

169193
@classmethod
170194
def get_config_type(cls) -> type[LoggingConfig]:

0 commit comments

Comments
 (0)