LoginSignup
11
8

More than 3 years have passed since last update.

ロガーの設定手順

  1. アプリケーション全体で使う名前をつける.
  2. ハンドラを設定.
  3. (フィルタの設定).
  4. フォーマッタの設定.

ハンドラ

  • ログをどこに出力するか(コンソール?ファイル?)を決める.
  • よく使うのは StreamHandler : コンソール、 FileHandler : ファイル
  • 組み合わせて設定することも可能.

フォーマッタ

  • ログの表示形式を決める.

時刻のフォーマットについて

日本時間に設定したい場合は、 Formatter.converter 属性をいじる必要がある。

Formatter.convertertime.struct_time を返す callableなので、そのような適当な関数を定義しておく.


def customTime(*args):
    return datetime.now(timezone('Asia/Tokyo')).timetuple()

.timetuple() で得られる struct_timeにタイムゾーン情報を含める方法ご存知でしたら、コメントいただきたいです。

設定例

main.py

import logging
from pytz import timezone
from datetime import datetime

# loggerに命名する. この名前で呼び出すことで他のモジュールにも以下の設定が引き継がれる.
logger = logging.getLogger("example")
logger.setLevel(logging.DEBUG)
# コンソールに出力するハンドラの設定
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
def customTime(*args):
    return datetime.now(timezone('Asia/Tokyo')).timetuple()
formatter = logging.Formatter(
    fmt='%(levelname)s : %(asctime)s : %(message)s',
    datefmt="%Y-%m-%d %H:%M:%S %z"
)
formatter.converter = customTime
sh.setFormatter(formatter)
# ファイルに出力するハンドラの設定
fh = logging.FileHandler("logs/example.log")
fh.setLevel(logging.DEBUG)
def customTime(*args):
    return datetime.now(timezone('Asia/Tokyo')).timetuple()
formatter = logging.Formatter(
    fmt='%(levelname)s : %(asctime)s : %(message)s',
    datefmt="%Y-%m-%d %H:%M:%S %z"
)
formatter.converter = customTime
fh.setFormatter(formatter)
logger.addHandler(sh)
logger.addHandler(fh)
11
8
1

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
11
8