add logger
This commit is contained in:
1 parent
1acd8846ab
commit
bf7b53c8e8
41 files changed
+1832
-694
No files matched your search
@@ -39,7 +39,9 @@ from app.video.schemas.video_schema import (
|
||||
from app.video.worker.video_task import download_and_upload_video_to_blob
|
||||
from app.utils.creatomate import CreatomateService
|
||||
from app.utils.pagination import PaginatedResponse
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger("video")
|
||||
|
||||
router = APIRouter(prefix="/video", tags=["video"])
|
||||
|
||||
@@ -115,7 +117,7 @@ async def generate_video(
|
||||
from app.database.session import AsyncSessionLocal
|
||||
|
||||
request_start = time.perf_counter()
|
||||
print(f"[generate_video] START - task_id: {task_id}, orientation: {orientation}")
|
||||
logger.info(f"[generate_video] START - task_id: {task_id}, orientation: {orientation}")
|
||||
|
||||
# ==========================================================================
|
||||
# 1단계: DB 조회 및 초기 데이터 저장 (세션을 명시적으로 열고 닫음)
|
||||
@@ -168,13 +170,13 @@ async def generate_video(
|
||||
)
|
||||
|
||||
query_time = time.perf_counter()
|
||||
print(f"[generate_video] Queries completed - task_id: {task_id}, "
|
||||
logger.debug(f"[generate_video] Queries completed - task_id: {task_id}, "
|
||||
f"elapsed: {(query_time - request_start)*1000:.1f}ms")
|
||||
|
||||
# ===== 결과 처리: Project =====
|
||||
project = project_result.scalar_one_or_none()
|
||||
if not project:
|
||||
print(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
|
||||
logger.warning(f"[generate_video] Project NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Project를 찾을 수 없습니다.",
|
||||
@@ -184,7 +186,7 @@ async def generate_video(
|
||||
# ===== 결과 처리: Lyric =====
|
||||
lyric = lyric_result.scalar_one_or_none()
|
||||
if not lyric:
|
||||
print(f"[generate_video] Lyric NOT FOUND - task_id: {task_id}")
|
||||
logger.warning(f"[generate_video] Lyric NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Lyric을 찾을 수 없습니다.",
|
||||
@@ -194,7 +196,7 @@ async def generate_video(
|
||||
# ===== 결과 처리: Song =====
|
||||
song = song_result.scalar_one_or_none()
|
||||
if not song:
|
||||
print(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
|
||||
logger.warning(f"[generate_video] Song NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 Song을 찾을 수 없습니다.",
|
||||
@@ -220,14 +222,14 @@ async def generate_video(
|
||||
# ===== 결과 처리: Image =====
|
||||
images = image_result.scalars().all()
|
||||
if not images:
|
||||
print(f"[generate_video] Image NOT FOUND - task_id: {task_id}")
|
||||
logger.warning(f"[generate_video] Image NOT FOUND - task_id: {task_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"task_id '{task_id}'에 해당하는 이미지를 찾을 수 없습니다.",
|
||||
)
|
||||
image_urls = [img.img_url for img in images]
|
||||
|
||||
print(
|
||||
logger.info(
|
||||
f"[generate_video] Data loaded - task_id: {task_id}, "
|
||||
f"project_id: {project_id}, lyric_id: {lyric_id}, "
|
||||
f"song_id: {song_id}, images: {len(image_urls)}"
|
||||
@@ -246,14 +248,14 @@ async def generate_video(
|
||||
await session.commit()
|
||||
video_id = video.id
|
||||
stage1_time = time.perf_counter()
|
||||
print(f"[generate_video] Video saved - task_id: {task_id}, id: {video_id}, "
|
||||
logger.info(f"[generate_video] Video saved - task_id: {task_id}, id: {video_id}, "
|
||||
f"stage1_elapsed: {(stage1_time - request_start)*1000:.1f}ms")
|
||||
# 세션이 여기서 자동으로 닫힘 (async with 블록 종료)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"[generate_video] DB EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
logger.error(f"[generate_video] DB EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
task_id=task_id,
|
||||
@@ -267,16 +269,16 @@ async def generate_video(
|
||||
# ==========================================================================
|
||||
stage2_start = time.perf_counter()
|
||||
try:
|
||||
print(f"[generate_video] Stage 2 START - Creatomate API - task_id: {task_id}")
|
||||
logger.info(f"[generate_video] Stage 2 START - Creatomate API - task_id: {task_id}")
|
||||
creatomate_service = CreatomateService(
|
||||
orientation=orientation,
|
||||
target_duration=song_duration,
|
||||
)
|
||||
print(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song_duration})")
|
||||
logger.debug(f"[generate_video] Using template_id: {creatomate_service.template_id}, duration: {creatomate_service.target_duration} (song duration: {song_duration})")
|
||||
|
||||
# 6-1. 템플릿 조회 (비동기)
|
||||
template = await creatomate_service.get_one_template_data_async(creatomate_service.template_id)
|
||||
print(f"[generate_video] Template fetched - task_id: {task_id}")
|
||||
logger.debug(f"[generate_video] Template fetched - task_id: {task_id}")
|
||||
|
||||
# 6-2. elements에서 리소스 매핑 생성
|
||||
modifications = creatomate_service.elements_connect_resource_blackbox(
|
||||
@@ -285,7 +287,7 @@ async def generate_video(
|
||||
lyric=lyrics,
|
||||
music_url=music_url,
|
||||
)
|
||||
print(f"[generate_video] Modifications created - task_id: {task_id}")
|
||||
logger.debug(f"[generate_video] Modifications created - task_id: {task_id}")
|
||||
|
||||
# 6-3. elements 수정
|
||||
new_elements = creatomate_service.modify_element(
|
||||
@@ -293,20 +295,20 @@ async def generate_video(
|
||||
modifications,
|
||||
)
|
||||
template["source"]["elements"] = new_elements
|
||||
print(f"[generate_video] Elements modified - task_id: {task_id}")
|
||||
logger.debug(f"[generate_video] Elements modified - task_id: {task_id}")
|
||||
|
||||
# 6-4. duration 확장
|
||||
final_template = creatomate_service.extend_template_duration(
|
||||
template,
|
||||
creatomate_service.target_duration,
|
||||
)
|
||||
print(f"[generate_video] Duration extended to {creatomate_service.target_duration}s - task_id: {task_id}")
|
||||
logger.debug(f"[generate_video] Duration extended to {creatomate_service.target_duration}s - task_id: {task_id}")
|
||||
|
||||
# 6-5. 커스텀 렌더링 요청 (비동기)
|
||||
render_response = await creatomate_service.make_creatomate_custom_call_async(
|
||||
final_template["source"],
|
||||
)
|
||||
print(f"[generate_video] Creatomate API response - task_id: {task_id}, response: {render_response}")
|
||||
logger.debug(f"[generate_video] Creatomate API response - task_id: {task_id}, response: {render_response}")
|
||||
|
||||
# 렌더 ID 추출
|
||||
if isinstance(render_response, list) and len(render_response) > 0:
|
||||
@@ -317,14 +319,14 @@ async def generate_video(
|
||||
creatomate_render_id = None
|
||||
|
||||
stage2_time = time.perf_counter()
|
||||
print(
|
||||
logger.info(
|
||||
f"[generate_video] Stage 2 DONE - task_id: {task_id}, "
|
||||
f"render_id: {creatomate_render_id}, "
|
||||
f"stage2_elapsed: {(stage2_time - stage2_start)*1000:.1f}ms"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
logger.error(f"[generate_video] Creatomate API EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
# 외부 API 실패 시 Video 상태를 failed로 업데이트
|
||||
from app.database.session import AsyncSessionLocal
|
||||
async with AsyncSessionLocal() as update_session:
|
||||
@@ -347,7 +349,7 @@ async def generate_video(
|
||||
# 3단계: creatomate_render_id 업데이트 (새 세션으로 빠르게 처리)
|
||||
# ==========================================================================
|
||||
stage3_start = time.perf_counter()
|
||||
print(f"[generate_video] Stage 3 START - DB update - task_id: {task_id}")
|
||||
logger.info(f"[generate_video] Stage 3 START - DB update - task_id: {task_id}")
|
||||
try:
|
||||
from app.database.session import AsyncSessionLocal
|
||||
async with AsyncSessionLocal() as update_session:
|
||||
@@ -361,11 +363,11 @@ async def generate_video(
|
||||
|
||||
stage3_time = time.perf_counter()
|
||||
total_time = stage3_time - request_start
|
||||
print(
|
||||
logger.debug(
|
||||
f"[generate_video] Stage 3 DONE - task_id: {task_id}, "
|
||||
f"stage3_elapsed: {(stage3_time - stage3_start)*1000:.1f}ms"
|
||||
)
|
||||
print(
|
||||
logger.info(
|
||||
f"[generate_video] SUCCESS - task_id: {task_id}, "
|
||||
f"render_id: {creatomate_render_id}, "
|
||||
f"total_time: {total_time*1000:.1f}ms"
|
||||
@@ -380,7 +382,7 @@ async def generate_video(
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[generate_video] Update EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
logger.error(f"[generate_video] Update EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
task_id=task_id,
|
||||
@@ -439,11 +441,11 @@ async def get_video_status(
|
||||
succeeded 상태인 경우 백그라운드에서 MP4 파일을 다운로드하고
|
||||
Video 테이블의 status를 completed로, result_movie_url을 업데이트합니다.
|
||||
"""
|
||||
print(f"[get_video_status] START - creatomate_render_id: {creatomate_render_id}")
|
||||
logger.info(f"[get_video_status] START - creatomate_render_id: {creatomate_render_id}")
|
||||
try:
|
||||
creatomate_service = CreatomateService()
|
||||
result = await creatomate_service.get_render_status_async(creatomate_render_id)
|
||||
print(f"[get_video_status] Creatomate API response - creatomate_render_id: {creatomate_render_id}, status: {result.get('status')}")
|
||||
logger.debug(f"[get_video_status] Creatomate API response - creatomate_render_id: {creatomate_render_id}, status: {result.get('status')}")
|
||||
|
||||
status = result.get("status", "unknown")
|
||||
video_url = result.get("url")
|
||||
@@ -481,7 +483,7 @@ async def get_video_status(
|
||||
store_name = project.store_name if project else "video"
|
||||
|
||||
# 백그라운드 태스크로 MP4 다운로드 → Blob 업로드 → DB 업데이트 → 임시 파일 삭제
|
||||
print(f"[get_video_status] Background task args - task_id: {video.task_id}, video_url: {video_url}, store_name: {store_name}")
|
||||
logger.info(f"[get_video_status] Background task args - task_id: {video.task_id}, video_url: {video_url}, store_name: {store_name}")
|
||||
background_tasks.add_task(
|
||||
download_and_upload_video_to_blob,
|
||||
task_id=video.task_id,
|
||||
@@ -489,7 +491,7 @@ async def get_video_status(
|
||||
store_name=store_name,
|
||||
)
|
||||
elif video and video.status == "completed":
|
||||
print(f"[get_video_status] SKIPPED - Video already completed, creatomate_render_id: {creatomate_render_id}")
|
||||
logger.debug(f"[get_video_status] SKIPPED - Video already completed, creatomate_render_id: {creatomate_render_id}")
|
||||
|
||||
render_data = VideoRenderData(
|
||||
id=result.get("id"),
|
||||
@@ -498,7 +500,7 @@ async def get_video_status(
|
||||
snapshot_url=result.get("snapshot_url"),
|
||||
)
|
||||
|
||||
print(f"[get_video_status] SUCCESS - creatomate_render_id: {creatomate_render_id}")
|
||||
logger.info(f"[get_video_status] SUCCESS - creatomate_render_id: {creatomate_render_id}")
|
||||
return PollingVideoResponse(
|
||||
success=True,
|
||||
status=status,
|
||||
@@ -511,7 +513,7 @@ async def get_video_status(
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
print(f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
|
||||
logger.error(f"[get_video_status] EXCEPTION - creatomate_render_id: {creatomate_render_id}, error: {e}")
|
||||
return PollingVideoResponse(
|
||||
success=False,
|
||||
status="error",
|
||||
@@ -563,7 +565,7 @@ async def download_video(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> DownloadVideoResponse:
|
||||
"""task_id로 Video 상태를 polling하고 completed 시 Project 정보와 영상 URL을 반환합니다."""
|
||||
print(f"[download_video] START - task_id: {task_id}")
|
||||
logger.info(f"[download_video] START - task_id: {task_id}")
|
||||
try:
|
||||
# task_id로 Video 조회 (여러 개 있을 경우 가장 최근 것 선택)
|
||||
video_result = await session.execute(
|
||||
@@ -575,7 +577,7 @@ async def download_video(
|
||||
video = video_result.scalar_one_or_none()
|
||||
|
||||
if not video:
|
||||
print(f"[download_video] Video NOT FOUND - task_id: {task_id}")
|
||||
logger.warning(f"[download_video] Video NOT FOUND - task_id: {task_id}")
|
||||
return DownloadVideoResponse(
|
||||
success=False,
|
||||
status="not_found",
|
||||
@@ -583,11 +585,11 @@ async def download_video(
|
||||
error_message="Video not found",
|
||||
)
|
||||
|
||||
print(f"[download_video] Video found - task_id: {task_id}, status: {video.status}")
|
||||
logger.debug(f"[download_video] Video found - task_id: {task_id}, status: {video.status}")
|
||||
|
||||
# processing 상태인 경우
|
||||
if video.status == "processing":
|
||||
print(f"[download_video] PROCESSING - task_id: {task_id}")
|
||||
logger.debug(f"[download_video] PROCESSING - task_id: {task_id}")
|
||||
return DownloadVideoResponse(
|
||||
success=True,
|
||||
status="processing",
|
||||
@@ -597,7 +599,7 @@ async def download_video(
|
||||
|
||||
# failed 상태인 경우
|
||||
if video.status == "failed":
|
||||
print(f"[download_video] FAILED - task_id: {task_id}")
|
||||
logger.error(f"[download_video] FAILED - task_id: {task_id}")
|
||||
return DownloadVideoResponse(
|
||||
success=False,
|
||||
status="failed",
|
||||
@@ -612,7 +614,7 @@ async def download_video(
|
||||
)
|
||||
project = project_result.scalar_one_or_none()
|
||||
|
||||
print(f"[download_video] COMPLETED - task_id: {task_id}, result_movie_url: {video.result_movie_url}")
|
||||
logger.info(f"[download_video] COMPLETED - task_id: {task_id}, result_movie_url: {video.result_movie_url}")
|
||||
return DownloadVideoResponse(
|
||||
success=True,
|
||||
status="completed",
|
||||
@@ -625,7 +627,7 @@ async def download_video(
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[download_video] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
logger.error(f"[download_video] EXCEPTION - task_id: {task_id}, error: {e}")
|
||||
return DownloadVideoResponse(
|
||||
success=False,
|
||||
status="error",
|
||||
@@ -674,7 +676,7 @@ async def get_videos(
|
||||
pagination: PaginationParams = Depends(get_pagination_params),
|
||||
) -> PaginatedResponse[VideoListItem]:
|
||||
"""완료된 영상 목록을 페이지네이션하여 반환합니다."""
|
||||
print(f"[get_videos] START - page: {pagination.page}, page_size: {pagination.page_size}")
|
||||
logger.info(f"[get_videos] START - page: {pagination.page}, page_size: {pagination.page_size}")
|
||||
try:
|
||||
offset = (pagination.page - 1) * pagination.page_size
|
||||
|
||||
@@ -732,14 +734,14 @@ async def get_videos(
|
||||
page_size=pagination.page_size,
|
||||
)
|
||||
|
||||
print(
|
||||
logger.info(
|
||||
f"[get_videos] SUCCESS - total: {total}, page: {pagination.page}, "
|
||||
f"page_size: {pagination.page_size}, items_count: {len(items)}"
|
||||
)
|
||||
return response
|
||||
|
||||
except Exception as e:
|
||||
print(f"[get_videos] EXCEPTION - error: {e}")
|
||||
logger.error(f"[get_videos] EXCEPTION - error: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"영상 목록 조회에 실패했습니다: {str(e)}",
|
||||
|
||||
Reference in new issue
Block a user