add logger
This commit is contained in:
1 parent
1acd8846ab
commit
bf7b53c8e8
41 files changed
+1832
-694
No files matched your search
@@ -1,13 +1,13 @@
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from config import apikey_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = get_logger("chatgpt")
|
||||
|
||||
# fmt: off
|
||||
LYRICS_PROMPT_TEMPLATE_ORI = """
|
||||
@@ -298,13 +298,12 @@ class ChatgptService:
|
||||
if prompt is None:
|
||||
prompt = self.build_lyrics_prompt()
|
||||
|
||||
print(f"[ChatgptService] Generated Prompt (length: {len(prompt)})")
|
||||
logger.debug(f"[ChatgptService] Generated Prompt (length: {len(prompt)})")
|
||||
logger.info(f"[ChatgptService] Starting GPT request with model: {self.model}")
|
||||
|
||||
# GPT API 호출
|
||||
response = await self._call_gpt_api(prompt)
|
||||
|
||||
print(f"[ChatgptService] SUCCESS - Response length: {len(response)}")
|
||||
logger.info(f"[ChatgptService] SUCCESS - Response length: {len(response)}")
|
||||
return response
|
||||
|
||||
@@ -332,7 +331,7 @@ class ChatgptService:
|
||||
[OUTPUT REQUIREMENTS]
|
||||
- 5개 항목으로 구분: 타겟 고객, 핵심 차별점, 지역 특성, 시즌별 포인트
|
||||
- 각 항목은 줄바꿈으로 구분
|
||||
- 총 500자 이내로 요약
|
||||
- 총 800자 이내로 요약
|
||||
- 내용의 누락이 있어서는 안된다
|
||||
- 문장이 자연스러워야 한다
|
||||
- 핵심 정보만 간결하게 포함
|
||||
|
||||
+10
-11
@@ -30,16 +30,16 @@ response = await creatomate.make_creatomate_call(template_id, modifications)
|
||||
"""
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import time
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from config import apikey_settings, creatomate_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = get_logger("creatomate")
|
||||
|
||||
|
||||
# Orientation 타입 정의
|
||||
@@ -76,14 +76,14 @@ async def close_shared_client() -> None:
|
||||
if _shared_client is not None and not _shared_client.is_closed:
|
||||
await _shared_client.aclose()
|
||||
_shared_client = None
|
||||
print("[CreatomateService] Shared HTTP client closed")
|
||||
logger.info("[CreatomateService] Shared HTTP client closed")
|
||||
|
||||
|
||||
def clear_template_cache() -> None:
|
||||
"""템플릿 캐시를 전체 삭제합니다."""
|
||||
global _template_cache
|
||||
_template_cache.clear()
|
||||
print("[CreatomateService] Template cache cleared")
|
||||
logger.info("[CreatomateService] Template cache cleared")
|
||||
|
||||
|
||||
def _is_cache_valid(cached_at: float) -> bool:
|
||||
@@ -164,7 +164,6 @@ class CreatomateService:
|
||||
httpx.HTTPError: 요청 실패 시
|
||||
"""
|
||||
logger.info(f"[Creatomate] {method} {url}")
|
||||
print(f"[Creatomate] {method} {url}")
|
||||
|
||||
client = await get_shared_client()
|
||||
|
||||
@@ -180,7 +179,6 @@ class CreatomateService:
|
||||
raise ValueError(f"Unsupported HTTP method: {method}")
|
||||
|
||||
logger.info(f"[Creatomate] Response - Status: {response.status_code}")
|
||||
print(f"[Creatomate] Response - Status: {response.status_code}")
|
||||
return response
|
||||
|
||||
async def get_all_templates_data(self) -> dict:
|
||||
@@ -210,12 +208,12 @@ class CreatomateService:
|
||||
if use_cache and template_id in _template_cache:
|
||||
cached = _template_cache[template_id]
|
||||
if _is_cache_valid(cached["cached_at"]):
|
||||
print(f"[CreatomateService] Cache HIT - {template_id}")
|
||||
logger.debug(f"[CreatomateService] Cache HIT - {template_id}")
|
||||
return copy.deepcopy(cached["data"])
|
||||
else:
|
||||
# 만료된 캐시 삭제
|
||||
del _template_cache[template_id]
|
||||
print(f"[CreatomateService] Cache EXPIRED - {template_id}")
|
||||
logger.debug(f"[CreatomateService] Cache EXPIRED - {template_id}")
|
||||
|
||||
# API 호출
|
||||
url = f"{self.BASE_URL}/v1/templates/{template_id}"
|
||||
@@ -228,7 +226,7 @@ class CreatomateService:
|
||||
"data": data,
|
||||
"cached_at": time.time(),
|
||||
}
|
||||
print(f"[CreatomateService] Cache MISS - {template_id} (cached)")
|
||||
logger.debug(f"[CreatomateService] Cache MISS - {template_id} (cached)")
|
||||
|
||||
return copy.deepcopy(data)
|
||||
|
||||
@@ -444,12 +442,13 @@ class CreatomateService:
|
||||
if animation["transition"]:
|
||||
total_template_duration -= animation["duration"]
|
||||
except Exception as e:
|
||||
print(f"[calc_scene_duration] Error processing element: {elem}, {e}")
|
||||
logger.error(f"[calc_scene_duration] Error processing element: {elem}, {e}")
|
||||
|
||||
return total_template_duration
|
||||
|
||||
def extend_template_duration(self, template: dict, target_duration: float) -> dict:
|
||||
"""템플릿의 duration을 target_duration으로 확장합니다."""
|
||||
target_duration += 0.1 # 수동으로 직접 변경 및 테스트 필요 : 파란박스 생기는것
|
||||
template["duration"] = target_duration
|
||||
total_template_duration = self.calc_scene_duration(template)
|
||||
extend_rate = target_duration / total_template_duration
|
||||
@@ -466,7 +465,7 @@ class CreatomateService:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
animation["duration"] = animation["duration"] * extend_rate
|
||||
except Exception as e:
|
||||
print(
|
||||
logger.error(
|
||||
f"[extend_template_duration] Error processing element: {elem}, {e}"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
"""
|
||||
FastAPI용 로깅 모듈
|
||||
|
||||
Django 로거 구조를 참고하여 FastAPI에 최적화된 로깅 시스템.
|
||||
|
||||
사용 예시:
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger("song")
|
||||
logger.info("노래 생성 완료")
|
||||
logger.error("오류 발생", exc_info=True)
|
||||
|
||||
로그 레벨:
|
||||
1. DEBUG: 디버깅 목적
|
||||
2. INFO: 일반 정보
|
||||
3. WARNING: 경고 정보 (작은 문제)
|
||||
4. ERROR: 오류 정보 (큰 문제)
|
||||
5. CRITICAL: 아주 심각한 문제
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from typing import Literal
|
||||
|
||||
from config import log_settings
|
||||
|
||||
# 로그 디렉토리 설정 (config.py의 LogSettings에서 관리)
|
||||
LOG_DIR = log_settings.get_log_dir()
|
||||
|
||||
# 로그 레벨 타입
|
||||
LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
|
||||
|
||||
|
||||
class LoggerConfig:
|
||||
"""로거 설정 클래스 (config.py의 LogSettings 참조)"""
|
||||
|
||||
# 출력 대상 설정 (LogSettings에서 가져옴)
|
||||
CONSOLE_ENABLED: bool = log_settings.LOG_CONSOLE_ENABLED
|
||||
FILE_ENABLED: bool = log_settings.LOG_FILE_ENABLED
|
||||
|
||||
# 기본 설정 (LogSettings에서 가져옴)
|
||||
DEFAULT_LEVEL: str = log_settings.LOG_LEVEL
|
||||
CONSOLE_LEVEL: str = log_settings.LOG_CONSOLE_LEVEL
|
||||
FILE_LEVEL: str = log_settings.LOG_FILE_LEVEL
|
||||
MAX_BYTES: int = log_settings.LOG_MAX_SIZE_MB * 1024 * 1024
|
||||
BACKUP_COUNT: int = log_settings.LOG_BACKUP_COUNT
|
||||
ENCODING: str = "utf-8"
|
||||
|
||||
# 포맷 설정 (LogSettings에서 가져옴)
|
||||
CONSOLE_FORMAT: str = log_settings.LOG_CONSOLE_FORMAT
|
||||
FILE_FORMAT: str = log_settings.LOG_FILE_FORMAT
|
||||
DATE_FORMAT: str = log_settings.LOG_DATE_FORMAT
|
||||
|
||||
|
||||
def _create_console_handler() -> logging.StreamHandler:
|
||||
"""콘솔 핸들러 생성"""
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setLevel(getattr(logging, LoggerConfig.CONSOLE_LEVEL))
|
||||
formatter = logging.Formatter(
|
||||
fmt=LoggerConfig.CONSOLE_FORMAT,
|
||||
datefmt=LoggerConfig.DATE_FORMAT,
|
||||
style="{",
|
||||
)
|
||||
handler.setFormatter(formatter)
|
||||
return handler
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 공유 파일 핸들러 (싱글톤)
|
||||
# 모든 로거가 동일한 파일 핸들러를 공유하여 하나의 로그 파일에 기록
|
||||
# =============================================================================
|
||||
_shared_file_handler: RotatingFileHandler | None = None
|
||||
_shared_error_handler: RotatingFileHandler | None = None
|
||||
|
||||
|
||||
def _get_shared_file_handler() -> RotatingFileHandler:
|
||||
"""
|
||||
공유 파일 핸들러 반환 (싱글톤)
|
||||
|
||||
모든 로거가 하나의 기본 로그 파일(app.log)에 기록합니다.
|
||||
파일명: logs/{날짜}_app.log
|
||||
"""
|
||||
global _shared_file_handler
|
||||
|
||||
if _shared_file_handler is None:
|
||||
today = datetime.today().strftime("%Y-%m-%d")
|
||||
log_file = LOG_DIR / f"{today}_app.log"
|
||||
|
||||
_shared_file_handler = RotatingFileHandler(
|
||||
filename=log_file,
|
||||
maxBytes=LoggerConfig.MAX_BYTES,
|
||||
backupCount=LoggerConfig.BACKUP_COUNT,
|
||||
encoding=LoggerConfig.ENCODING,
|
||||
)
|
||||
_shared_file_handler.setLevel(getattr(logging, LoggerConfig.FILE_LEVEL))
|
||||
formatter = logging.Formatter(
|
||||
fmt=LoggerConfig.FILE_FORMAT,
|
||||
datefmt=LoggerConfig.DATE_FORMAT,
|
||||
style="{",
|
||||
)
|
||||
_shared_file_handler.setFormatter(formatter)
|
||||
|
||||
return _shared_file_handler
|
||||
|
||||
|
||||
def _get_shared_error_handler() -> RotatingFileHandler:
|
||||
"""
|
||||
공유 에러 파일 핸들러 반환 (싱글톤)
|
||||
|
||||
모든 로거의 ERROR 이상 로그가 하나의 에러 로그 파일(error.log)에 기록됩니다.
|
||||
파일명: logs/{날짜}_error.log
|
||||
"""
|
||||
global _shared_error_handler
|
||||
|
||||
if _shared_error_handler is None:
|
||||
today = datetime.today().strftime("%Y-%m-%d")
|
||||
log_file = LOG_DIR / f"{today}_error.log"
|
||||
|
||||
_shared_error_handler = RotatingFileHandler(
|
||||
filename=log_file,
|
||||
maxBytes=LoggerConfig.MAX_BYTES,
|
||||
backupCount=LoggerConfig.BACKUP_COUNT,
|
||||
encoding=LoggerConfig.ENCODING,
|
||||
)
|
||||
_shared_error_handler.setLevel(logging.ERROR)
|
||||
formatter = logging.Formatter(
|
||||
fmt=LoggerConfig.FILE_FORMAT,
|
||||
datefmt=LoggerConfig.DATE_FORMAT,
|
||||
style="{",
|
||||
)
|
||||
_shared_error_handler.setFormatter(formatter)
|
||||
|
||||
return _shared_error_handler
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def get_logger(name: str = "app") -> logging.Logger:
|
||||
"""
|
||||
로거 인스턴스 반환 (캐싱 적용)
|
||||
|
||||
Args:
|
||||
name: 로거 이름 (모듈명 권장: "song", "lyric", "video" 등)
|
||||
|
||||
Returns:
|
||||
설정된 로거 인스턴스
|
||||
|
||||
Example:
|
||||
logger = get_logger("song")
|
||||
logger.info("노래 처리 시작")
|
||||
"""
|
||||
logger = logging.getLogger(name)
|
||||
|
||||
# 이미 핸들러가 설정된 경우 반환
|
||||
if logger.handlers:
|
||||
return logger
|
||||
|
||||
# 로그 레벨 설정
|
||||
logger.setLevel(getattr(logging, LoggerConfig.DEFAULT_LEVEL))
|
||||
|
||||
# 핸들러 추가 (설정에 따라 선택적으로 추가)
|
||||
if LoggerConfig.CONSOLE_ENABLED:
|
||||
logger.addHandler(_create_console_handler())
|
||||
|
||||
if LoggerConfig.FILE_ENABLED:
|
||||
logger.addHandler(_get_shared_file_handler())
|
||||
logger.addHandler(_get_shared_error_handler())
|
||||
|
||||
# 상위 로거로 전파 방지 (중복 출력 방지)
|
||||
logger.propagate = False
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
def setup_uvicorn_logging() -> dict:
|
||||
"""
|
||||
Uvicorn 서버의 로깅 설정을 반환합니다.
|
||||
|
||||
============================================================
|
||||
언제 사용하는가?
|
||||
============================================================
|
||||
Uvicorn 서버를 Python 코드로 직접 실행할 때 사용합니다.
|
||||
CLI 명령어(uvicorn main:app --reload)로 실행할 때는 적용되지 않습니다.
|
||||
|
||||
============================================================
|
||||
사용 방법
|
||||
============================================================
|
||||
1. Python 코드에서 uvicorn.run() 호출 시:
|
||||
|
||||
# run.py 또는 main.py 하단
|
||||
import uvicorn
|
||||
from app.utils.logger import setup_uvicorn_logging
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(
|
||||
"main:app",
|
||||
host="0.0.0.0",
|
||||
port=8000,
|
||||
reload=True,
|
||||
log_config=setup_uvicorn_logging(), # 여기서 적용
|
||||
)
|
||||
|
||||
2. 실행:
|
||||
python run.py
|
||||
또는
|
||||
python main.py
|
||||
|
||||
============================================================
|
||||
어떤 동작을 하는가?
|
||||
============================================================
|
||||
Uvicorn의 기본 로깅 형식을 애플리케이션의 LogSettings와 일치시킵니다.
|
||||
|
||||
- formatters: 로그 출력 형식 정의
|
||||
- default: 일반 로그용 (서버 시작/종료, 에러 등)
|
||||
- access: HTTP 요청 로그용 (클라이언트 IP, 요청 경로, 상태 코드)
|
||||
|
||||
- handlers: 로그 출력 대상 설정
|
||||
- stdout으로 콘솔에 출력
|
||||
|
||||
- loggers: Uvicorn 내부 로거 설정
|
||||
- uvicorn: 메인 로거
|
||||
- uvicorn.error: 에러/시작/종료 로그
|
||||
- uvicorn.access: HTTP 요청 로그
|
||||
|
||||
============================================================
|
||||
출력 예시
|
||||
============================================================
|
||||
적용 전 (Uvicorn 기본):
|
||||
INFO: 127.0.0.1:52341 - "GET /docs HTTP/1.1" 200 OK
|
||||
INFO: Uvicorn running on http://0.0.0.0:8000
|
||||
|
||||
적용 후:
|
||||
[2026-01-14 15:30:00] INFO [uvicorn.access] 127.0.0.1 - "GET /docs HTTP/1.1" 200
|
||||
[2026-01-14 15:30:00] INFO [uvicorn:startup:45] Uvicorn running on http://0.0.0.0:8000
|
||||
|
||||
============================================================
|
||||
반환값 구조 (Python logging.config.dictConfig 형식)
|
||||
============================================================
|
||||
{
|
||||
"version": 1, # dictConfig 버전 (항상 1)
|
||||
"disable_existing_loggers": False, # 기존 로거 유지
|
||||
"formatters": { ... }, # 포맷터 정의
|
||||
"handlers": { ... }, # 핸들러 정의
|
||||
"loggers": { ... }, # 로거 정의
|
||||
}
|
||||
|
||||
Returns:
|
||||
dict: Uvicorn log_config 파라미터에 전달할 설정 딕셔너리
|
||||
"""
|
||||
return {
|
||||
# --------------------------------------------------------
|
||||
# dictConfig 버전 (필수, 항상 1)
|
||||
# --------------------------------------------------------
|
||||
"version": 1,
|
||||
|
||||
# --------------------------------------------------------
|
||||
# 기존 로거 비활성화 여부
|
||||
# False: 기존 로거 유지 (권장)
|
||||
# True: 기존 로거 모두 비활성화
|
||||
# --------------------------------------------------------
|
||||
"disable_existing_loggers": False,
|
||||
|
||||
# --------------------------------------------------------
|
||||
# 포맷터 정의
|
||||
# 로그 메시지의 출력 형식을 지정합니다.
|
||||
# --------------------------------------------------------
|
||||
"formatters": {
|
||||
# 일반 로그용 포맷터 (서버 시작/종료, 에러 등)
|
||||
"default": {
|
||||
"format": LoggerConfig.CONSOLE_FORMAT,
|
||||
"datefmt": LoggerConfig.DATE_FORMAT,
|
||||
"style": "{", # {변수명} 스타일 사용
|
||||
},
|
||||
# HTTP 요청 로그용 포맷터
|
||||
# 사용 가능한 변수: client_addr, request_line, status_code
|
||||
"access": {
|
||||
"format": "[{asctime}] {levelname:8} [{name}] {client_addr} - \"{request_line}\" {status_code}",
|
||||
"datefmt": LoggerConfig.DATE_FORMAT,
|
||||
"style": "{",
|
||||
},
|
||||
},
|
||||
|
||||
# --------------------------------------------------------
|
||||
# 핸들러 정의
|
||||
# 로그를 어디에 출력할지 지정합니다.
|
||||
# --------------------------------------------------------
|
||||
"handlers": {
|
||||
# 일반 로그 핸들러 (stdout 출력)
|
||||
"default": {
|
||||
"formatter": "default",
|
||||
"class": "logging.StreamHandler",
|
||||
"stream": "ext://sys.stdout",
|
||||
},
|
||||
# HTTP 요청 로그 핸들러 (stdout 출력)
|
||||
"access": {
|
||||
"formatter": "access",
|
||||
"class": "logging.StreamHandler",
|
||||
"stream": "ext://sys.stdout",
|
||||
},
|
||||
},
|
||||
|
||||
# --------------------------------------------------------
|
||||
# 로거 정의
|
||||
# Uvicorn 내부에서 사용하는 로거들을 설정합니다.
|
||||
# --------------------------------------------------------
|
||||
"loggers": {
|
||||
# Uvicorn 메인 로거
|
||||
"uvicorn": {
|
||||
"handlers": ["default"],
|
||||
"level": "INFO",
|
||||
"propagate": False, # 상위 로거로 전파 방지
|
||||
},
|
||||
# 에러/시작/종료 로그
|
||||
"uvicorn.error": {
|
||||
"handlers": ["default"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
# HTTP 요청 로그 (GET /path HTTP/1.1 200 등)
|
||||
"uvicorn.access": {
|
||||
"handlers": ["access"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# 편의를 위한 사전 정의된 로거 이름 상수
|
||||
HOME_LOGGER = "home"
|
||||
LYRIC_LOGGER = "lyric"
|
||||
SONG_LOGGER = "song"
|
||||
VIDEO_LOGGER = "video"
|
||||
CELERY_LOGGER = "celery"
|
||||
APP_LOGGER = "app"
|
||||
@@ -1,15 +1,15 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
import aiohttp
|
||||
import bs4
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from config import crawler_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = get_logger("scraper")
|
||||
|
||||
|
||||
class GraphQLException(Exception):
|
||||
@@ -109,7 +109,7 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
self.scrap_type = "GraphQL"
|
||||
|
||||
except GraphQLException:
|
||||
print("fallback")
|
||||
logger.debug("GraphQL failed, fallback to Playwright")
|
||||
self.scrap_type = "Playwright"
|
||||
pass # 나중에 pw 이용한 crawling으로 fallback 추가
|
||||
|
||||
@@ -138,7 +138,6 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
|
||||
try:
|
||||
logger.info(f"[NvMapScraper] Requesting place_id: {place_id}")
|
||||
print(f"[NvMapScraper] Requesting place_id: {place_id}")
|
||||
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
async with session.post(
|
||||
@@ -148,24 +147,20 @@ query getAccommodation($id: String!, $deviceType: String) {
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
logger.info(f"[NvMapScraper] SUCCESS - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] SUCCESS - place_id: {place_id}")
|
||||
return await response.json()
|
||||
|
||||
# 실패 상태 코드
|
||||
logger.error(f"[NvMapScraper] Failed with status {response.status} - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] 실패 상태 코드: {response.status}")
|
||||
raise GraphQLException(
|
||||
f"Request failed with status {response.status}"
|
||||
)
|
||||
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
logger.error(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||
raise CrawlingTimeoutException(f"Request timed out after {self.REQUEST_TIMEOUT}s")
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"[NvMapScraper] Client error: {e}")
|
||||
print(f"[NvMapScraper] Client error: {e}")
|
||||
raise GraphQLException(f"Client error: {e}")
|
||||
|
||||
async def _get_facility_string(self, place_id: str) -> str | None:
|
||||
|
||||
@@ -32,17 +32,17 @@ URL 경로 형식:
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
import httpx
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from config import azure_blob_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = get_logger("blob")
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (싱글톤 패턴)
|
||||
@@ -56,13 +56,13 @@ async def get_shared_blob_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is None or _shared_blob_client.is_closed:
|
||||
print("[AzureBlobUploader] Creating shared HTTP client...")
|
||||
logger.info("[AzureBlobUploader] Creating shared HTTP client...")
|
||||
_shared_blob_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(180.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
print("[AzureBlobUploader] Shared HTTP client created - "
|
||||
"max_connections: 20, max_keepalive: 10")
|
||||
logger.info("[AzureBlobUploader] Shared HTTP client created - "
|
||||
"max_connections: 20, max_keepalive: 10")
|
||||
return _shared_blob_client
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ async def close_shared_blob_client() -> None:
|
||||
if _shared_blob_client is not None and not _shared_blob_client.is_closed:
|
||||
await _shared_blob_client.aclose()
|
||||
_shared_blob_client = None
|
||||
print("[AzureBlobUploader] Shared HTTP client closed")
|
||||
logger.info("[AzureBlobUploader] Shared HTTP client closed")
|
||||
|
||||
|
||||
class AzureBlobUploader:
|
||||
@@ -158,15 +158,15 @@ class AzureBlobUploader:
|
||||
|
||||
try:
|
||||
logger.info(f"[{log_prefix}] Starting upload")
|
||||
print(f"[{log_prefix}] Getting shared client...")
|
||||
logger.debug(f"[{log_prefix}] Getting shared client...")
|
||||
|
||||
client = await get_shared_blob_client()
|
||||
client_time = time.perf_counter()
|
||||
elapsed_ms = (client_time - start_time) * 1000
|
||||
print(f"[{log_prefix}] Client acquired in {elapsed_ms:.1f}ms")
|
||||
logger.debug(f"[{log_prefix}] Client acquired in {elapsed_ms:.1f}ms")
|
||||
|
||||
print(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
logger.debug(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
|
||||
response = await asyncio.wait_for(
|
||||
client.put(upload_url, content=file_content, headers=headers),
|
||||
@@ -176,44 +176,38 @@ class AzureBlobUploader:
|
||||
duration_ms = (upload_time - start_time) * 1000
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
logger.info(f"[{log_prefix}] SUCCESS - Status: {response.status_code}")
|
||||
print(f"[{log_prefix}] SUCCESS - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Public URL: {self._last_public_url}")
|
||||
logger.info(f"[{log_prefix}] SUCCESS - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
logger.debug(f"[{log_prefix}] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
|
||||
# 업로드 실패
|
||||
logger.error(f"[{log_prefix}] FAILED - Status: {response.status_code}")
|
||||
print(f"[{log_prefix}] FAILED - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Response: {response.text[:500]}")
|
||||
logger.error(f"[{log_prefix}] FAILED - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
logger.error(f"[{log_prefix}] Response: {response.text[:500]}")
|
||||
return False
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s")
|
||||
print(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s")
|
||||
return False
|
||||
|
||||
except httpx.ConnectError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] CONNECT_ERROR: {e}")
|
||||
print(f"[{log_prefix}] CONNECT_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
logger.error(f"[{log_prefix}] CONNECT_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
except httpx.ReadError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] READ_ERROR: {e}")
|
||||
print(f"[{log_prefix}] READ_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
logger.error(f"[{log_prefix}] READ_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] ERROR: {type(e).__name__}: {e}")
|
||||
print(f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
logger.error(f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
async def _upload_file(
|
||||
@@ -241,7 +235,7 @@ class AzureBlobUploader:
|
||||
|
||||
upload_url = self._build_upload_url(category, file_name)
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
logger.debug(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
@@ -306,7 +300,7 @@ class AzureBlobUploader:
|
||||
upload_url = self._build_upload_url("song", file_name)
|
||||
self._last_public_url = self._build_public_url("song", file_name)
|
||||
log_prefix = "upload_music_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
logger.debug(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "audio/mpeg", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
@@ -368,7 +362,7 @@ class AzureBlobUploader:
|
||||
upload_url = self._build_upload_url("video", file_name)
|
||||
self._last_public_url = self._build_public_url("video", file_name)
|
||||
log_prefix = "upload_video_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
logger.debug(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "video/mp4", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
@@ -434,7 +428,7 @@ class AzureBlobUploader:
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
log_prefix = "upload_image_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
logger.debug(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
|
||||
Reference in new issue
Block a user