chore: improve validation and handler of logging timezone with TimezoneName (#9595)

This commit is contained in:
Bowen Liang 2024-10-30 11:18:23 +08:00 committed by GitHub
parent e74479717a
commit bab5c54219
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 10 additions and 12 deletions

View File

@ -10,6 +10,7 @@ from pydantic import (
PositiveInt,
computed_field,
)
from pydantic_extra_types.timezone_name import TimeZoneName
from pydantic_settings import BaseSettings
from configs.feature.hosted_service import HostedServiceConfig
@ -339,8 +340,9 @@ class LoggingConfig(BaseSettings):
default=None,
)
LOG_TZ: Optional[str] = Field(
description="Timezone for log timestamps (e.g., 'America/New_York')",
LOG_TZ: Optional[TimeZoneName] = Field(
description="Timezone for log timestamps. Allowed timezone values can be referred to IANA Time Zone Database,"
" e.g., 'America/New_York')",
default=None,
)

View File

@ -1,8 +1,10 @@
import logging
import os
import sys
from datetime import datetime
from logging.handlers import RotatingFileHandler
import pytz
from flask import Flask
from configs import dify_config
@ -30,16 +32,10 @@ def init_app(app: Flask):
handlers=log_handlers,
force=True,
)
log_tz = dify_config.LOG_TZ
if log_tz:
from datetime import datetime
import pytz
timezone = pytz.timezone(log_tz)
def time_converter(seconds):
return datetime.utcfromtimestamp(seconds).astimezone(timezone).timetuple()
for handler in logging.root.handlers:
handler.formatter.converter = time_converter
handler.formatter.converter = lambda seconds: (
datetime.fromtimestamp(seconds, tz=pytz.UTC).astimezone(log_tz).timetuple()
)