refactor(api): type log identity dict with IdentityDict TypedDict (#34485)

This commit is contained in:
YBoy
2026-04-03 04:25:02 +02:00
committed by GitHub
parent 9a6222f245
commit e178451d04

View File

@@ -3,13 +3,19 @@
import logging import logging
import traceback import traceback
from datetime import UTC, datetime from datetime import UTC, datetime
from typing import Any from typing import Any, TypedDict
import orjson import orjson
from configs import dify_config from configs import dify_config
class IdentityDict(TypedDict, total=False):
tenant_id: str
user_id: str
user_type: str
class StructuredJSONFormatter(logging.Formatter): class StructuredJSONFormatter(logging.Formatter):
""" """
JSON log formatter following the specified schema: JSON log formatter following the specified schema:
@@ -84,7 +90,7 @@ class StructuredJSONFormatter(logging.Formatter):
return log_dict return log_dict
def _extract_identity(self, record: logging.LogRecord) -> dict[str, str] | None: def _extract_identity(self, record: logging.LogRecord) -> IdentityDict | None:
tenant_id = getattr(record, "tenant_id", None) tenant_id = getattr(record, "tenant_id", None)
user_id = getattr(record, "user_id", None) user_id = getattr(record, "user_id", None)
user_type = getattr(record, "user_type", None) user_type = getattr(record, "user_type", None)
@@ -92,7 +98,7 @@ class StructuredJSONFormatter(logging.Formatter):
if not any([tenant_id, user_id, user_type]): if not any([tenant_id, user_id, user_type]):
return None return None
identity: dict[str, str] = {} identity: IdentityDict = {}
if tenant_id: if tenant_id:
identity["tenant_id"] = tenant_id identity["tenant_id"] = tenant_id
if user_id: if user_id: