From e178451d04e6442e10b698fa3a344ca9e65c80a6 Mon Sep 17 00:00:00 2001 From: YBoy Date: Fri, 3 Apr 2026 04:25:02 +0200 Subject: [PATCH] refactor(api): type log identity dict with IdentityDict TypedDict (#34485) --- api/core/logging/structured_formatter.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/api/core/logging/structured_formatter.py b/api/core/logging/structured_formatter.py index 4295d2dd34..9baf6c4682 100644 --- a/api/core/logging/structured_formatter.py +++ b/api/core/logging/structured_formatter.py @@ -3,13 +3,19 @@ import logging import traceback from datetime import UTC, datetime -from typing import Any +from typing import Any, TypedDict import orjson from configs import dify_config +class IdentityDict(TypedDict, total=False): + tenant_id: str + user_id: str + user_type: str + + class StructuredJSONFormatter(logging.Formatter): """ JSON log formatter following the specified schema: @@ -84,7 +90,7 @@ class StructuredJSONFormatter(logging.Formatter): 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) user_id = getattr(record, "user_id", 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]): return None - identity: dict[str, str] = {} + identity: IdentityDict = {} if tenant_id: identity["tenant_id"] = tenant_id if user_id: