본문 바로가기
MLOps/배포

FastAPI 로그 관리하기

by 해피ing 2024. 1. 30.
반응형

 

사전 준비

 

이전 블로그를 참고하여 로그 관리를 진행합니다.

 

FastAPI 로그 적용

 

FastAPI 로그 관리 폴더 구조입니다.

 

example/
├── app
│   └── main.py
├── docker-compose.yml
├── Dockerfile
└── requirements.txt

 

requirements.txt 파일에 loguru 패키지를 추가합니다.

 

파이썬 Loguru 패키지는 실행 중엔 발생하는 이벤트나 각종 메시지 등의 정보를 로그로 기록할 수 있습니다.

 

server@gpu:/$ sudo vim requirements.txt

ultralytics==8.0.42
uvicorn==0.20.0
fastapi==0.89.1
pandas
numpy
scikit-learn
seaborn
matplotlib
opencv-python
python-multipart
loguru

 

로그 정보를 기록하기 위해 main.py 파일을 수정합니다.

 

실행 결과는 FastAPI Status 패키지를 활용합니다.

 

실행 상태는 성공(200), 실패(404)로 구분합니다.

 

server@gpu:/$ sudo vim app/main.py

import sys
import os
from fastapi import FastAPI, UploadFile, File, Depends, APIRouter, Request, status
from typing import List
from loguru import logger

class Upload:
    def __init__(self, path: str):
        self.path = path
        
app = FastAPI()

logger.remove()
logger.add(sys.stdout, colorize=True, format='<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>')

router = APIRouter()

async def logging_dependency(request: Request):
    logger.info('')
    #logger.debug('Headers:')
    #for name, value in request.headers.items():
        #logger.debug(f'\t{name}: {value}')
        
@router.post('/upload')
async def upload_file(upload: Upload = Depends(Upload), files: List[UploadFile] = File(...)):
    try:
        os.makedirs(upload.path)
    finally:
        for file in files:
            names = f'{file.filename}'
            paths = os.path.join(upload.path, names)
            with open(paths, 'wb+') as f:
                f.write(file.file.read())
        return {'message': 'image saved successfully'}
    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='')
    
app.include_router(router, dependencies=[Depends(logging_dependency)])

 

FastAPI 실행

 

이전에 실행 중인 FastAPI 컨테이너를 모두 종료하고, 도커 이미지에 Loguru 패키지가 추가 되었기 때문에 --build 명령어를 추가해서 다시 시작합니다.

 

server@gpu:/$ docker compose down --volumes

[+] Running 2/2
 ✔ Container example-web-1  Removed                                                                                                                                                                                                                                   0.5s 
 ✔ Network example_default  Removed
 
server@gpu:/$ docker compose up -d --build

[+] Building 1.8s (13/13) FINISHED
.
.
.
[+] Running 2/2
 ✔ Network example_default  Created                                                                                                                                                                                                                                   0.1s 
 ✔ Container example-web-1  Started

 

FastAPI Swagger UI 실행 및 실패

 

다음은 성공 예시 입니다.

 

 

다음은 실패 예시 입니다.

 

FastAPI 로그 확인

 

FastAPI Swagger UI에서 실행된 결과는 docker logs -f 명령어로 확인할 수 있습니다.

 

server@gpu:/$ docker logs -f example-web-1

==========
== CUDA ==
==========

CUDA Version 12.0.0

Container image Copyright (c) 2016-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.

This container image and its contents are governed by the NVIDIA Deep Learning Container License.
By pulling and using the container, you accept the terms and conditions of this license:
https://developer.nvidia.com/ngc/nvidia-deep-learning-container-license

A copy of this license is made available in this container at /NGC-DL-CONTAINER-LICENSE for your convenience.

WARNING: The NVIDIA Driver was not detected.  GPU functionality will not be available.
   Use the NVIDIA Container Toolkit to start this container with GPU support; see
   https://docs.nvidia.com/datacenter/cloud-native/ .

*************************
** DEPRECATION NOTICE! **
*************************
THIS IMAGE IS DEPRECATED and is scheduled for DELETION.
    https://gitlab.com/nvidia/container-images/cuda/blob/master/doc/support-policy.md

INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     203.255.217.192:59890 - "GET /docs HTTP/1.1" 200 OK
INFO:     203.255.217.192:59890 - "GET /openapi.json HTTP/1.1" 200 OK
INFO:     203.255.217.192:59962 - "GET /docs HTTP/1.1" 200 OK
INFO:     203.255.217.192:59962 - "GET /openapi.json HTTP/1.1" 200 OK
17:57:25 | INFO | 
INFO:     203.255.217.192:59963 - "POST /upload?path=%2Fapp%2Fdata HTTP/1.1" 200 OK
Did not find CR at end of boundary (40)
INFO:     203.255.217.192:60017 - "POST /upload?path=%2Fapp%2Fdata HTTP/1.1" 400 Bad Request
반응형

'MLOps > 배포' 카테고리의 다른 글

FastAPI로 데이터 업로드하기  (0) 2024.01.30
우분투에서 도커로 FastAPI 환경 구축하기  (0) 2024.01.24