improve logging
This commit is contained in:
+6
-7
@@ -32,7 +32,7 @@ from pyrogram.types import Message
|
||||
from fastapi import FastAPI, HTTPException, Response, Request
|
||||
from fastapi.responses import HTMLResponse, FileResponse
|
||||
from telegram_client import TelegramClient
|
||||
from config import get_settings
|
||||
from config import get_settings, setup_logging
|
||||
from rss_generator import generate_channel_rss, generate_channel_html
|
||||
from post_parser import PostParser
|
||||
from url_signer import verify_media_digest, generate_media_digest
|
||||
@@ -58,18 +58,15 @@ class RequestLoggingMiddleware(BaseHTTPMiddleware):
|
||||
raise
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
if not logger.handlers:
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
|
||||
logger.addHandler(handler)
|
||||
if not logger.handlers: pass
|
||||
|
||||
client = TelegramClient()
|
||||
Config = get_settings()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
setup_logging(Config["log_level"])
|
||||
|
||||
base_cache_dir = os.path.abspath("./data/cache")
|
||||
os.makedirs(base_cache_dir, exist_ok=True) # Create cache directory
|
||||
|
||||
@@ -97,6 +94,8 @@ def mask_sensitive_value(input_str: str) -> str:
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
setup_logging(Config["log_level"])
|
||||
|
||||
logger.info("Starting server with configuration:")
|
||||
for key, value in Config.items():
|
||||
if any(sensitive in key.lower() for sensitive in ['token', 'tg_api_id', 'tg_api_hash']):
|
||||
|
||||
@@ -5,12 +5,40 @@
|
||||
# pylint: disable=broad-exception-raised, raise-missing-from, too-many-arguments, redefined-outer-name
|
||||
# pylint: disable=multiple-statements, logging-fstring-interpolation, trailing-whitespace, line-too-long
|
||||
# pylint: disable=broad-exception-caught, missing-function-docstring, missing-class-docstring
|
||||
# pylint: disable=f-string-without-interpolation
|
||||
# pylint: disable=f-string-without-interpolation, global-statement
|
||||
# pylance: disable=reportMissingImports, reportMissingModuleSource
|
||||
|
||||
import os
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
# Переменная для отслеживания состояния инициализации логгирования
|
||||
_LOGGING_INITIALIZED = False
|
||||
|
||||
def setup_logging(level_name: str = "INFO") -> None:
|
||||
global _LOGGING_INITIALIZED
|
||||
|
||||
if _LOGGING_INITIALIZED: return
|
||||
|
||||
level = getattr(logging, level_name.upper(), logging.INFO)
|
||||
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(level)
|
||||
|
||||
if not root_logger.handlers:
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setFormatter(formatter)
|
||||
root_logger.addHandler(console_handler)
|
||||
else:
|
||||
for handler in root_logger.handlers:
|
||||
handler.setFormatter(formatter)
|
||||
|
||||
logging.getLogger('uvicorn').setLevel(logging.WARNING)
|
||||
logging.getLogger('fastapi').setLevel(logging.WARNING)
|
||||
|
||||
_LOGGING_INITIALIZED = True
|
||||
logging.info("Logging system initialized")
|
||||
|
||||
def get_settings() -> dict[str, Any]:
|
||||
tg_api_id = os.getenv("TG_API_ID")
|
||||
tg_api_hash = os.getenv("TG_API_HASH")
|
||||
@@ -18,6 +46,8 @@ def get_settings() -> dict[str, Any]:
|
||||
print("TG_API_ID and TG_API_HASH must be set")
|
||||
os._exit(1)
|
||||
|
||||
log_level = os.getenv("LOG_LEVEL", "INFO")
|
||||
|
||||
return {
|
||||
"tg_api_id": int(tg_api_id),
|
||||
"tg_api_hash": tg_api_hash,
|
||||
@@ -25,7 +55,7 @@ def get_settings() -> dict[str, Any]:
|
||||
"api_host": os.getenv("API_HOST", "0.0.0.0"),
|
||||
"api_port": int(os.getenv("API_PORT") or 8000),
|
||||
"pyrogram_bridge_url": os.getenv("PYROGRAM_BRIDGE_URL", ""),
|
||||
"log_level": os.getenv("LOG_LEVEL", "INFO"),
|
||||
"log_level": log_level,
|
||||
"debug": os.getenv("DEBUG", "False") == "True",
|
||||
"token": os.getenv("TOKEN", ""),
|
||||
"time_based_merge": os.getenv("TIME_BASED_MERGE", "False").strip() in ["True", "true"],
|
||||
|
||||
@@ -23,13 +23,6 @@ from types import SimpleNamespace
|
||||
Config = get_settings()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
if not logger.handlers:
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
async def _create_time_based_media_groups(messages: list[Message], merge_seconds: int = 5) -> list[Message]:
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user