[Python] Logger

ログファイルを作成する時は logging モジュールを使う

# -*- coding: utf-8 -*-
import logging

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='./test.log',
filemode='w')

logging.debug("A debug message")
logging.info("An info message")
logging.warning("A warning message")
logging.error("An error message")
logging.critical("A critical message")
logging.exception("An exception message")

出力結果 (test.log)

2011-02-11 14:41:44 DEBUG A debug message
2011-02-11 14:41:44 INFO An info message
2011-02-11 14:41:44 WARNING A warning message
2011-02-11 14:41:44 ERROR An error message
2011-02-11 14:41:44 CRITICAL A critical message
2011-02-11 14:41:44 ERROR An exception message
None

ログレベルを設定, ログファイルに追記する場合

# -*- coding: utf-8 -*-
import logging

logging.basicConfig(level=logging.WARNING,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='./test.log',
filemode='a')

logging.debug("A debug message")
logging.info("An info message")
logging.warning("A warning message")
logging.error("An error message")
logging.critical("A critical message")
logging.exception("An exception message")

出力結果 (test.log)

2011-02-11 14:42:45 WARNING A warning message
2011-02-11 14:42:45 ERROR An error message
2011-02-11 14:42:45 CRITICAL A critical message
2011-02-11 14:42:45 ERROR An exception message
None