Logging between classes in 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 the开发者_运维百科re way to handle it better? How I can pass the logger between classes except using contructors?
Perhaps python supports something like static method in Java, so I can write like Logger.info(message) in all three classes?
Another way probably could be redirecting global sys.stdout to the file, i.e specifying
logger = open('debug.txt', 'w')
sys.stdout = logger
Then using calls sys.stdout in all classes.
What do you think?
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!")
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.
精彩评论