Это строка форматирования, которую я использую для ведения журнала:
'%(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
Как я могу сказать регистратору использовать правильный контекст для имени функции? Я думаю, что это будет на самом деле на два уровня выше на стеке.
ИЗМЕНИТЬ
Это тестовая программа, показывающая проблему:
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?