Я бы помещал вызовы на logging.debug
в верхней части каждой функции / метода обработчика событий в моем коде GUI, который представляет «действие пользователя», то есть щелчки мыши, ввод ключа. Также любая высокоуровневая функция, которая обновляет представление, будет иметь вызов logging.debug
в начале. Эти сообщения журнала будут содержать любую важную информацию, используемую в функции / методе. Поскольку сообщения регистрируются на уровне DEBUG
, их можно включить / выключить простым изменением конфигурации.
В качестве альтернативы, хотя она и не сложна, может быть быстрее забыть даже модуль logging
и временно ввести операторы print
, пока вы не найдете проблему.
Вот код, который я написал для инициализации модуля logging
с помощью вращающегося файла журнала:
import pytz
timestamp_detailed_format = '%Y-%m-%d %H:%M:%S.%f %Z'
def detailed_format(date):
u"Given a datetime object return a detailed representation including fractional seconds and time zone"
return unicode(date.strftime(timestamp_detailed_format))
def localize_epoch_time(epoch_time, timezone=pytz.UTC):
u"Given an epoch time return an accurate, timezone-aware datetime object"
t = localtime(epoch_time)
epochdt = datetime(*(t[:6] + (int((epoch_time - long(epoch_time)) * 1000000),))).astimezone(timezone)
if hasattr(timezone, 'normalize'): # pytz tzinfo objects have this
return timezone.normalize(epochdt)
else: # tzinfo object not from pytz module
return epochdt
class TimezoneAwareFormatter(logging.Formatter):
u"custom log formatter using timezone-aware timestamps"
def __init__(self, logformat=None, timezone=pytz.UTC):
logging.Formatter.__init__(self, logformat)
self._timezone = timezone
def formatTime(self, record, _=None):
u"times will be formatted as YYYY-MM-DD HH:MM:SS.ssssss TZ"
return detailed_format(localize_epoch_time(record.created, self._timezone))
def simple_log_file(filename, logname=None, level=logging.NOTSET,
threshold=10485760, generations=2, quiet=False, timezone=pytz.UTC):
u"initialize logging API for a simple generational log file, return logger object"
formatter = TimezoneAwareFormatter('%(asctime)s %(levelname)s %(message)s', timezone)
handler = logging.handlers.RotatingFileHandler(filename, 'a', threshold, generations, 'UTF-8')
handler.setFormatter(formatter)
logger = logging.getLogger(logname)
logger.addHandler(handler)
logger.setLevel(level)
if not quiet: logger.info(u'Logging to this destination has started')
return logger