LoginSignup
53
55

More than 5 years have passed since last update.

djangoのloggerの(最低限の)使い方

Posted at
  • 正確にはpythonのlogger
  • djangoではsettings.pyに設定書いてつかう
  • 他にもいろいろ凝ったことが出来るがまずは最低限だけ

settings.pyに下記のような設定を書く

LOGGING = {
    'version': 1,   # これを設定しないと怒られる
    'formatters': { # 出力フォーマットを文字列形式で指定する
        'all': {    # 出力フォーマットに`all`という名前をつける
            'format': '\t'.join([
                "[%(levelname)s]",
                "asctime:%(asctime)s",
                "module:%(module)s",
                "message:%(message)s",
                "process:%(process)d",
                "thread:%(thread)d",
            ])
        },
    },
    'handlers': {  # ログをどこに出すかの設定
        'file': {  # どこに出すかの設定に名前をつける `file`という名前をつけている
            'level': 'DEBUG',  # DEBUG以上のログを取り扱うという意味
            'class': 'logging.FileHandler',  # ログを出力するためのクラスを指定
            'filename': os.path.join(BASE_DIR, 'django.log'),  # どこに出すか
            'formatter': 'all',  # どの出力フォーマットで出すかを名前で指定
        },
        'console': { # どこに出すかの設定をもう一つ、こちらの設定には`console`という名前
            'level': 'DEBUG',
            # こちらは標準出力に出してくれるクラスを指定
            'class': 'logging.StreamHandler', 
            'formatter': 'all'
        },
    },
    'loggers': {  # どんなloggerがあるかを設定する
        'command': {  # commandという名前のloggerを定義
            'handlers': ['file', 'console'],  # 先述のfile, consoleの設定で出力
            'level': 'DEBUG',
        },
    },
}

こんな関数を作って呼ぶ

def info(msg):
    logger = logging.getLogger('command')
    logger.info(msg)

info("hello!")

django.logと標準出力に下記の形式で出力される

[INFO]  asctime:2015-09-23 16:27:11,291 module:my_module_name   message:hello!  process:97649   thread:140735161512704

公式のドキュメントには設定例がいくつかある: https://docs.djangoproject.com/en/1.8/topics/logging/#examples

53
55
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
53
55