我已经通过日志记录模块文档阅读,虽然我可能错过了一些明显的东西,我得到的代码似乎没有按预期工作。我正在使用Python 2.6.4。Python记录多个文件
我的程序由几个不同的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:如何从多个文件进行日志记录?
哇, 发现。我有logging.basicConfig()仍然在我的一些其他模块中使用。我从未想到他们可能会造成问题。谢谢! – Loix0 2010-01-09 00:12:46