使用 Python 日志记录管理记录器
我正在编写一个服务器应用程序,它应该能够在控制台和日志文件上以不同级别进行日志记录。
问题是,如果设置了logging.basicConfig(),它将记录到控制台,但必须在主线程中设置。
也可以使用 logging.basicConfig(filename='logger.log')
设置以写入文件。
设置控制台日志记录 (logging.StreamHandler()
) 或文件日志记录 (logging.FileHandler()
) 的句柄是对 logging.baseconfig()
的补充。代码>选项集。
问题是,设置不是独立的。 我的意思是,logging.baseConfig()的日志级别必须包含Handler级别,否则不会被记录。
因此,如果我将 baseConfig
设置为记录到文件,并将 StreamHandler
设置为记录到控制台,则文件日志级别必须低于控制台级别。 (此外,basicConfig 选项会记录所有其他日志。)
我尝试创建两个句柄,一个用于控制台,一个用于日志文件,它们可以工作,但是无论 指定什么日志类型basicConfig()
仍将显示重复消息。
有没有办法禁用 basicConfig()
的输出? 或者还有其他方式来实现这些选项吗?
I'm writing a server app which should be able to log at different levels both on the console and a log file.
The problem is, if logging.basicConfig()
is set it will log to the console but it must be set in the main thread.
It can also be set with logging.basicConfig(filename='logger.log')
to write to a file.
Setting a handle either for console logging (logging.StreamHandler()
) or file logging (logging.FileHandler()
) complements the logging.baseconfig()
option set.
The problem is, that the settings are not independent.
What I mean is, the loglevel of logging.baseConfig()
must include the Handler level, or it wont be logged.
So if I set the baseConfig
to log to file, and a StreamHandler
to log to console, the file loglevel must be lower than the console level.
(Also, the basicConfig
option logs all other logs.)
I tried to create two Handles, one for the console and one for the log file, they work, but whatever log type is specified by basicConfig()
will still be displayed duplicating messages.
Is there a way to disable the output of basicConfig()
?
Or any other way to implement these options?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在问题中没有确切说明您想要在控制台和文件日志记录上达到什么级别。但是,您不需要调用
basicConfig()
,因为它只是一个便利函数。您可以执行例如(刚刚输入的代码,未测试):首先将事件传递给记录器,如果要处理事件(由于比较记录器和事件的级别),则将事件传递给每个记录器记录器的处理程序及其所有祖先的处理程序。如果在处理程序上设置了级别,则该处理程序可能会删除该事件,否则它将输出该事件。
You don't say in your question exactly what levels you want on your console and file logging. However, you don't need to call
basicConfig()
, as it's only a convenience function. You can do e.g. (code just typed in, not tested):Events are passed to the logger first, and if an event is to be processed (due to comparing the level of the logger and the event) then the event is passed to each handler of the logger and all its ancestors' handlers as well. If a level is set on a handler the event may be dropped by that handler, otherwise it will output the event.
找到下面的示例代码来处理各种异常的日志记录
Find the below example code to handle the logging with all kind of exceptions