これは、ログに使用している書式設定文字列です。
'%(asctime)s - %(levelname)-10s - %(funcName)s - %(message)s'
しかし、ログ メッセージを表示するために、もう少し処理を行うラッパーがあります (さまざまなログ レベルをセットアップし、さまざまなログ バックエンドを構成し、カスタム レベルにアクセスするための便利な関数を提供するなど):
class MyLogger(logging.Logger):
def split_line(self, level, message):
....
self.log.(level, line)
def progress(self, message):
self.split_line(PROGRESS, message)
この設定では、何かをログに記録するたびに:
def myfunc():
log.progress('Hello')
私は得る:
013-10-27 08:47:30,130 - PROGRESS - split_line - Hello
これは私が望んでいたものではありません。つまり、これは次のとおりです。
013-10-27 08:47:30,130 - PROGRESS - myfunc - Hello
関数名に正しいコンテキストを使用するようにロガーに指示するにはどうすればよいですか? これは、実際にはスタックフレームで 2 レベル高くなると思います。
編集
これは、問題を示すテスト プログラムです。
import sys
import logging
PROGRESS = 1000
class MyLogger(logging.Logger):
PROGRESS = PROGRESS
LOG_FORMATTER = '%(asctime)s - %(levelname)-10s - %(funcName)s - %(message)s'
DEF_LOGGING_LEVEL = logging.WARNING
def __init__(self, log_name, level=None):
logging.Logger.__init__(self, log_name)
self.formatter = logging.Formatter(self.LOG_FORMATTER)
self.initLogger(level)
def initLogger(self, level=None):
self.setLevel(level or self.DEF_LOGGING_LEVEL)
self.propagate = False
def add_handler(self, log_file, use_syslog):
if use_syslog : hdlr = logging.handlers.SysLogHandler(address='/dev/log')
elif log_file : hdlr = logging.FileHandler(log_file)
else : hdlr = logging.StreamHandler(sys.stderr)
hdlr.setFormatter(self.formatter)
self.addHandler(hdlr)
return hdlr
def addHandlers(self, log_file=None, progress_file=None, use_syslog=False):
self.logger_hdlr = self.add_handler(log_file, use_syslog)
if progress_file:
self.progress_hdlr = self.add_handler(progress_file, use_syslog)
self.progress_hdlr.setLevel(self.PROGRESS)
else:
self.progress_hdlr = None
def split_line(self, level, txt, *args):
txt = txt % (args)
for line in txt.split('\n'):
self.log(level, line)
def progress(self, txt, *args):
self.split_line(self.PROGRESS, txt, *args)
logging.setLoggerClass(MyLogger)
logging.addLevelName(PROGRESS, 'PROGRESS')
logger = logging.getLogger(__name__)
logger.addHandlers()
name = 'John'
logger.progress('Hello %s\nHow are you doing?', name)
プロデュース:
2013-10-27 09:47:39,577 - PROGRESS - split_line - Hello John
2013-10-27 09:47:39,577 - PROGRESS - split_line - How are you doing?