概要
FastAPIでアプリケーションを作成しDockerで動かす際に、標準出力へログを出す方法を記載します。
logging
モジュールかprint()
で行います。
環境
Python:3.12
FastAPI:0.111.0
Docker:26.1.1, build 4cf5afa
print()で行う場合
簡易的なログ出力であれば、print()
で可能です。
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
print(f"print: {item.name}")
return {"return": f"hello {item.name}"}
出力結果
print: hogehoge
以前はprint()だと標準出力されない現象があったようです。1
Python3.12で検証したところ、普通に出力されました。
loggingモジュールを使う場合
FastAPIでuvicorn
というWebサーバが動作しています。
そのなかですでにlogging
を使っているため、logging.getLogger
でインスタンス化します。
from fastapi import FastAPI
from pydantic import BaseModel
import logging
logger = logging.getLogger("uvicorn.myapp")
class Item(BaseModel):
name: str
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
logger.info(f"logging: {item.name}")
return {"return": f"hello {item.name}"}
出力結果
INFO: logging: hogehoge