LoginSignup
20
25

More than 5 years have passed since last update.

Pythonでロギングをきちんと

Last updated at Posted at 2017-02-16

はじめに

自分用のめもです。

コード

main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import othermodule

LOG_LEVEL = 'DEBUG'

if __name__ == '__main__':

    logging.basicConfig(
        level=getattr(logging, LOG_LEVEL),
        format='%(asctime)s [%(levelname)s] %(module)s | %(message)s',
        datefmt='%Y/%m/%d %H:%M:%S',
    )

    # test
    logger = logging.getLogger(__name__)
    logger.critical('critical message')
    logger.error('error message')
    logger.warning('warning message')
    logger.info('info message')
    logger.debug('debug message')
    othermodule.test()
othermodule.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging

def test():
    _logger = logging.getLogger(__name__)
    _logger.critical('critical message')
    _logger.error('error message')
    _logger.warning('warning message')
    _logger.info('info message')
    _logger.debug('debug message')
$ python main.py
2017/01/01 00:00:00 [CRITICAL] main | critical message
2017/01/01 00:00:00 [ERROR] main | error message
2017/01/01 00:00:00 [WARNING] main | warning message
2017/01/01 00:00:00 [DEBUG] main | info message
2017/01/01 00:00:00 [INFO] main | debug message
2017/01/01 00:00:00 [CRITICAL] othermodule | critical message
2017/01/01 00:00:00 [ERROR] othermodule | error message
2017/01/01 00:00:00 [WARNING] othermodule | warning message
2017/01/01 00:00:00 [DEBUG] othermodule | info message
2017/01/01 00:00:00 [INFO] othermodule | debug message

説明その他

  • level=getattr(logging, LOG_LEVEL) configなどから取得した文字列からログレベルをセットすることを想定
  • logging#debug とか使っちゃうとモジュールで分けられずルートロガーにぶっこまれるので、ちゃんと logging#getLogger で適切なロガーを取ってくる
  • logging#basicConfig でルートロガーを設定すると、importで使っているモジュールのロガーも一括で設定できる
  • logging#basicConfig しないと StreamHandler (標準出力にログを出力するハンドラ)が生成されず、コンソール出力されない
属性 説明
%(asctime)s datefmt に従うログ生成時間
%(levelname)s ログレベルの名前
%(module)s モジュール名
%(message)s ログメッセージ
20
25
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
20
25