在python中的类之间记录 [英] Logging between classes in python
问题描述
我在python中有三个类,它们在不同的线程中运行.我想将所有类的输出都输出到相同的文件中.现在,我在主类中创建了输出方法,并将其通过构造函数传递给其他类.有办法更好地处理它吗?除构造函数外,如何在类之间传递记录器?
I have three classes in python and they run in different threads. I would like to have output to the same file from all classes. Right now I created output method in main class and passing it through constructors to other classes. Is there way to handle it better? How I can pass the logger between classes except using contructors?
也许python在Java中支持静态方法之类的东西,所以我可以在所有三个类中都写Logger.info(message)吗?
Perhaps python supports something like static method in Java, so I can write like Logger.info(message) in all three classes?
另一种方法可能是将全局sys.stdout重定向到文件,即指定
Another way probably could be redirecting global sys.stdout to the file, i.e specifying
logger = open('debug.txt', 'w')
sys.stdout = logger
然后在所有类中使用sys.stdout调用.
Then using calls sys.stdout in all classes.
您怎么看?
推荐答案
import logging
log = logging.getLogger("mylog")
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s")
# Alternative formatting available on python 3.2+:
# formatter = logging.Formatter(
# "{asctime} {threadName:>11} {levelname} {message}", style='{')
# Log to file
filehandler = logging.FileHandler("debug.txt", "w")
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(formatter)
log.addHandler(filehandler)
# Log to stdout too
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.INFO)
streamhandler.setFormatter(formatter)
log.addHandler(streamhandler)
# Test it
log.debug("Some message")
log.error("An error!")
try:
something()
except:
log.exception("An exception occured!")
并进入debug.txt:
And get in debug.txt:
2011-01-18 12:07:24,943 MainThread DEBUG Some message
2011-01-18 12:07:24,943 MainThread ERROR An error!
2011-01-18 12:07:24,943 MainThread ERROR An exception occured!
Traceback (most recent call last):
File "./logtest.py", line 17, in
something()
NameError: name 'something' is not defined
请注意,消息在日志文件中的显示顺序可能与从多个线程进行日志记录时发生的顺序不完全相同.
Note that the order in which the messages appear in the log file may not correspond exactly to the order in which they happened when you're logging from several threads.
这篇关于在python中的类之间记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!