【发布时间】:2010-04-22 09:02:49
【问题描述】:
事情是这样的:
我正在尝试将日志记录模块与 wx.App() 的重定向功能相结合。我的意图是将文件 AND 记录到 stderr。但我希望 stderr/stdout 重定向到一个单独的框架,这是 wx.App 的功能。
我的测试代码:
import logging
import wx
class MyFrame(wx.Frame):
def __init__(self):
self.logger = logging.getLogger("main.MyFrame")
wx.Frame.__init__(self, parent = None, id = wx.ID_ANY, title = "MyFrame")
self.logger.debug("MyFrame.__init__() called.")
def OnExit(self):
self.logger.debug("MyFrame.OnExit() called.")
class MyApp(wx.App):
def __init__(self, redirect):
self.logger = logging.getLogger("main.MyApp")
wx.App.__init__(self, redirect = redirect)
self.logger.debug("MyApp.__init__() called.")
def OnInit(self):
self.frame = MyFrame()
self.frame.Show()
self.SetTopWindow(self.frame)
self.logger.debug("MyApp.OnInit() called.")
return True
def OnExit(self):
self.logger.debug("MyApp.OnExit() called.")
def main():
logger_formatter = logging.Formatter("%(name)s\t%(levelname)s\t%(message)s")
logger_stream_handler = logging.StreamHandler()
logger_stream_handler.setLevel(logging.INFO)
logger_stream_handler.setFormatter(logger_formatter)
logger_file_handler = logging.FileHandler("test.log", mode = "w")
logger_file_handler.setLevel(logging.DEBUG)
logger_file_handler.setFormatter(logger_formatter)
logger = logging.getLogger("main")
logger.setLevel(logging.DEBUG)
logger.addHandler(logger_stream_handler)
logger.addHandler(logger_file_handler)
logger.info("Logger configured.")
app = MyApp(redirect = True)
logger.debug("Created instance of MyApp. Calling MainLoop().")
app.MainLoop()
logger.debug("MainLoop() ended.")
logger.info("Exiting program.")
return 0
if (__name__ == "__main__"):
main()
预期的行为是:
- 创建一个名为 test.log
的文件
- 该文件包含级别为 DEBUG 和 INFO/ERROR/WARNING/CRITICAL
的日志消息
- 来自 INFO 和 ERROR/WARNING/CRITICAL 类型的消息要么显示在控制台上,要么显示在单独的框架中,具体取决于它们的创建位置
- 不在 MyApp 或 MyFrame 中的记录器消息显示在控制台
- 来自 MyApp 或 MyFrame 内部的记录器消息显示在单独的框架中
实际行为是:
- 文件已创建并包含:
main INFO Logger configured.
main.MyFrame DEBUG MyFrame.__init__() called.
main.MyFrame INFO MyFrame.__init__() called.
main.MyApp DEBUG MyApp.OnInit() called.
main.MyApp INFO MyApp.OnInit() called.
main.MyApp DEBUG MyApp.__init__() called.
main DEBUG Created instance of MyApp. Calling MainLoop().
main.MyApp DEBUG MyApp.OnExit() called.
main DEBUG MainLoop() ended.
main INFO Exiting program.
- 控制台输出为:
main INFO Logger configured.
main.MyFrame INFO MyFrame.__init__() called.
main.MyApp INFO MyApp.OnInit() called.
main INFO Exiting program.
- 没有打开单独的框架,虽然行
main.MyFrame INFO MyFrame.__init__() called.
main.MyApp INFO MyApp.OnInit() called.
应该显示在框架内而不是控制台上。
在我看来,一旦记录器实例使用 stderr 作为输出,wx.App 就无法将 stderr 重定向到帧。 wxPythons Docs 声明了想要的行为,see here.
有什么想法吗?
Uwe
【问题讨论】: