【发布时间】:2011-01-03 03:15:17
【问题描述】:
我已经阅读了日志模块文档,虽然我可能遗漏了一些明显的东西,但我得到的代码似乎并没有按预期工作。我正在使用 Python 2.6.4。
我的程序由几个不同的 python 文件组成,我想从这些文件中将日志消息发送到文本文件,并可能发送到屏幕。我想这是很常见的事情,所以我在某个地方搞砸了。
我的代码现在正在做的是正确地记录到文本文件,有点。但是登录到屏幕是重复的,一个具有指定格式,一个没有。另外,当我关闭屏幕输出时,我仍然会打印一次文本,这是我不想要的 - 我只想将它记录到文件中。
无论如何,一些代码:
#logger.py
import logging
from logging.handlers import RotatingFileHandler
import os
def setup_logging(logdir=None, scrnlog=True, txtlog=True, loglevel=logging.DEBUG):
logdir = os.path.abspath(logdir)
if not os.path.exists(logdir):
os.mkdir(logdir)
log = logging.getLogger('stumbler')
log.setLevel(loglevel)
log_formatter = logging.Formatter("%(asctime)s - %(levelname)s :: %(message)s")
if txtlog:
txt_handler = RotatingFileHandler(os.path.join(logdir, "Stumbler.log"), backupCount=5)
txt_handler.doRollover()
txt_handler.setFormatter(log_formatter)
log.addHandler(txt_handler)
log.info("Logger initialised.")
if scrnlog:
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
log.addHandler(console_handler)
那里没什么异常。
#core.py
import logging
corelog = logging.getLogger('stumbler.core') # From what I understand of the docs, this should work :/
class Stumbler:
[...]
corelog.debug("Messages and rainbows...")
屏幕输出显示了它是如何被复制的:
2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3
DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir1/music.mp3
2010-01-08 22:57:07,587 - DEBUG :: SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe
DEBUG:stumbler.core:SCANZIP: Checking zip contents, file: testscandir/testdir2/subdir/executable.exe
虽然文本文件得到了格式正确的输出,但在 logger.py 中关闭屏幕登录仍然会显示格式不正确的输出。
根据我对文档的了解,调用 corelog.debug(),看到 corelog 是“stumbler”记录器的子级,它应该使用这种格式并输出日志。
为这样一个琐碎问题的文章道歉。
TL;DR:如何从多个文件进行日志记录?
【问题讨论】:
标签: python logging error-logging