Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Created September 28, 2011 01:31
Show Gist options
  • Select an option

  • Save PyYoshi/1246774 to your computer and use it in GitHub Desktop.

Select an option

Save PyYoshi/1246774 to your computer and use it in GitHub Desktop.
カスタムLogger
# -*- coding:utf-8 -*-
__AUTHOR__ = 'PyYoshi'
__LICENCE__ = 'MIT'
__VERSION__ = '0.1'
# fork: http://www.ueblog.org/blog/entry/pythonlogging/
# History:
# 0.1: First commit and modified...
# ファイルへパスなのかディレクトリへのパスなのか紛らわしいのでlogfile_pathをlogfile_dirpathに変更した。
# enableがTrueかFalseで出力するか切り替えするように変更した。
# start(),end()以外の出力関数の引数messageを必須に変更した。
# logfile_dirpathが存在しない場合os.makedirsで作成する
# Memo:
#
# Usage:
# _ = CustomLogger('/var/log/','testapp',True)
# _.start()
# _.debug('hoge')
# _.info('Huga')
# _.error('Foo')
# _.warning('Bar')
# _.critical('Uhyo')
# _.end()
#
import os
import logging
import logging.config
class CustomLogger(object):
def __init__(self, logfile_dirpath, appname,enable=False):
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S' ) #BasicConfigを指定して標準出力に表示する
if not os.path.exists(logfile_dirpath):
os.makedirs(logfile_path)
logfile = os.path.join(logfile_dirpath, "%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サーバー
'[email protected]', #FROM メールアドレス
[
'[email protected]',
'[email protected]',
], #送付先 メールアドレス
'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')
self.enable = enable
def start(self, message=''):
if self.enable:
self.start_logger.debug(message)
def debug(self, message):
if self.enable:
self.body_logger.debug(message)
def info(self, message):
if self.enable:
self.body_logger.info(message)
def warning(self, message):
if self.enable:
self.body_logger.warning(message)
def error(self, message):
if self.enable:
self.body_logger.error(message)
def critical(self, message):
if self.enable:
self.body_logger.critical(message)
def end(self, message=''):
if self.enable:
self.end_logger.debug(message)
if __name__ == "__main__":
# enable=Trueの時にlogを発行する
logger = CustomLogger(".", "test",enable=True)
logger.start()
logger.debug("debug")
logger.error("error")
logger.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment