Pythonのlogging
February 21, 2009 at 10:44 PM | View CommentsこれまでPythonのモジュールでloggingモジュールをちゃんと使って無かったので練習。
(ちょっと問題ですね)
14.5 logging -- Python 用ロギング機能
- 特定のファイルにdebug以上のログを書き込み。プロジェクトごとにログファイルを作り、開始日時と終了日時も記録。
- 標準出力にも表示
- error以上はメールにエラーメッセージを送付
をするために試しに以下のコードを書いてみました。
#! vim: fileencoding=utf8
import os
import logging
import logging.config
class CustomLogger(object):
def __init__(self, logfile_path, appname):
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S' ) #BasicConfigを指定して標準出力に表示する
logfile = os.path.join(logfile_path, "%s.log" % appname)
start_log = logging.FileHandler(logfile)
start_log.setFormatter(logging.Formatter(
"--- START --- %(asctime)s %(message)s",
datefmt='%Y-%m-%d %H:%M:%S')
)
start_log.setLevel(logging.DEBUG)
end_log = logging.FileHandler(logfile)
end_log.setFormatter(logging.Formatter(
"--- END --- %(asctime)s %(message)s",
datefmt='%Y-%m-%d %H:%M:%S')
)
end_log.setLevel(logging.DEBUG)
fmt = "[%(asctime)s] %(pathname)s %(levelname)s line:%(lineno)d %(message)s"
body_log = logging.FileHandler(logfile)
body_log.setFormatter(logging.Formatter(
fmt = fmt,
datefmt='%H:%M:%S')
)
body_log.setLevel(logging.DEBUG)
email_log = logging.handlers.SMTPHandler(
'your.smtp.server', #SMTPサーバー
'your_from@hoge.com', #FROM メールアドレス
[
'to_addr1@hoge.com',
'to_addr2@hoge.com',
], #送付先 メールアドレス
'ERROR MESSAGE' #件名
)
email_log.setFormatter(logging.Formatter(
fmt = fmt,
datefmt='%H:%M:%S'))
email_log.setLevel(logging.ERROR)
# Bodyというloggerにbody_logとemail_logハンドラーを追加(ハンドラーは複数追加できる)、
#StartとEndにそれぞれstart_log,end_logハンドラーを追加
logging.getLogger('Body').addHandler(body_log)
logging.getLogger('Body').addHandler(email_log)
logging.getLogger('Start').addHandler(start_log)
logging.getLogger('End').addHandler(end_log)
self.start_logger = logging.getLogger('Start')
self.end_logger = logging.getLogger('End')
self.body_logger = logging.getLogger('Body')
def start(self, message=''):
self.start_logger.debug(message)
def debug(self, message=''):
self.body_logger.debug(message)
def info(self, message=''):
self.body_logger.info(message)
def warning(self, message=''):
self.body_logger.warning(message)
def error(self, message=''):
self.body_logger.error(message)
def critical(self, message=''):
self.body_logger.critical(message)
def end(self, message=''):
self.end_logger.debug(message)
if __name__ == "__main__":
logger = CustomLogger(".", "test")
logger.start()
logger.debug("debug")
logger.error("error")
logger.end()
激しく冗長な気もしますが、一応期待通りに
標準出力に
C:\temp\>python log.py
2009-02-21 20:19:07 DEBUG
2009-02-21 20:19:07 DEBUG debug
2009-02-21 20:19:07 ERROR error
2009-02-21 20:19:07 DEBUG
カレントディレクトのtest.logが生成
--- START --- 2009-02-21 20:19:07
[20:19:07] log.py DEBUG line:69 debug
[20:19:07] log.py ERROR line:78 error
--- END --- 2009-02-21 20:19:07
メールに件名 ERROR MESSAGEで
[20:19:07] log.py ERROR line:78 error
と表示されました。
ソースコードにメールアドレスなど直書きとか酷いので、もうちょっと直してから使う予定。
(setSMTPHandlerみたいなメソッド作れば良いか?)
みんなどんな風にloggingを使っているのだろう??
categories:
python
ツイート