PLBA2-2. Реализация

This commit is contained in:
2026-10-10 19:36:32 +03:00
parent 473cde126f
commit 71998a6b13
120 changed files with 3675 additions and 21 deletions
+3
View File
@@ -0,0 +1,3 @@
from plba.logging.technical import TechnicalJsonFormatter, create_stdout_handler
__all__ = ["TechnicalJsonFormatter", "create_stdout_handler"]
+57
View File
@@ -0,0 +1,57 @@
from collections.abc import Mapping, Callable
from datetime import datetime, timezone
import json
import logging
import sys
from typing import Any, TextIO
from plba.tracing.context import current_business_trace_id
class TechnicalJsonFormatter(logging.Formatter):
def __init__(
self,
application_id: str,
trace_id_reader: Callable[[], str | None] = current_business_trace_id,
) -> None:
super().__init__()
if not application_id:
raise ValueError("application_id must be non-empty")
self._application_id = application_id
self._trace_id_reader = trace_id_reader
def format(self, record: logging.LogRecord) -> str:
timestamp = datetime.fromtimestamp(record.created, timezone.utc)
payload: dict[str, Any] = {
"timestamp": timestamp.isoformat(timespec="milliseconds").replace(
"+00:00", "Z"
),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"application_id": self._application_id,
}
attributes = getattr(record, "attributes", None)
if attributes is not None:
if not isinstance(attributes, Mapping) or any(
not isinstance(key, str) for key in attributes
):
raise ValueError("log attributes must be a string-keyed object")
payload["attributes"] = dict(attributes)
business_trace_id = self._trace_id_reader()
if business_trace_id is not None:
payload["business_trace_id"] = business_trace_id
try:
return json.dumps(
payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")
)
except (TypeError, ValueError) as error:
raise ValueError("technical log attributes must be JSON-safe") from error
def create_stdout_handler(
application_id: str, stream: TextIO | None = None
) -> logging.StreamHandler[TextIO]:
handler = logging.StreamHandler(stream if stream is not None else sys.stdout)
handler.setFormatter(TechnicalJsonFormatter(application_id))
return handler