0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Docker内でFastAPIを使うときのログ出力

Posted at

概要

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

参考

[小ネタ]uvicornとlogging

  1. 以下の記事に記載されています。
    Why doesn't Python app print anything when run in a detached docker container?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?