LoginSignup
5
7

More than 3 years have passed since last update.

pythonのログ出力方法

Last updated at Posted at 2021-04-15

概要

pythonのアプリでログを簡単に設定できる方法を記載します
私の場合はfastapiを使って実装しましたのでその例と交えて説明します。

  • 導入のメリット

    • カスタマイズしやすい
    • 設定が一箇所に集約できる
    • フレームワーク依存がない
  • デメリット

    • python 3.8以上である必要がある

logのwrapperを作る

logutil.py
import logging
import os

logging.basicConfig(format='%(levelname)s:%(asctime)s:%(pathname)s:%(lineno)s:%(message)s')
logger = logging.getLogger(__name__)

if os.environ['ENV'] == "prd":
    logger.setLevel(logging.INFO)
else:
    logger.setLevel(logging.DEBUG)    

def debug(message):
    logger.debug(message, stacklevel=2)

def info(message):
    logger.info(message, stacklevel=2)

def error(message):
    logger.error(message, stacklevel=2)

実際の呼び出し例

hello.py
import logutil as log

log.info("hello")

ポイント

  • 環境変数を渡してあげることによって、ログレベルを分岐できます

例)こんな感じで渡してあげるとロード時に読み込んでくれます。

export env=prd
  • python3.8以上でないといけない理由 stacklevel=2
    • wrapperをしている都合上、呼び出しもとのソース行数を表示したいと思います。この宣言をすると呼び出しもののソース行を表示してくれます。
5
7
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
5
7