日志机制的区别:API 和应用程序(python) [英] difference in logging mechanism: API and application(python)
问题描述
我目前正在编写一个 API 和一个使用该 API 的应用程序.我从人们那里得到了一些建议,他们说我应该在应用程序中使用处理程序执行日志记录,并使用记录器"对象从 API 进行日志记录.
I am currently writing an API and an application which uses the API. I have gotten suggestions from people stating that I should perform logging using handlers in the application and use a "logger" object for logging from the API.
根据我上面收到的建议,以下实现是否正确?
In light of the advice I received above, is the following implementation correct?
class test:
def __init__(self, verbose):
self.logger = logging.getLogger("test")
self.logger.setLevel(verbose)
def do_something(self):
# do something
self.logger.log("something")
# by doing this i get the error message "No handlers could be found for logger "test"
我想到的实现如下:
#!/usr/bin/python
"""
....
....
create a logger with a handler
....
....
"""
myobject = test()
try:
myobject.do_something()
except SomeError:
logger.log("cant do something")
我想让我的基础知识扎实,我
非常感谢您对代码的任何帮助和建议,我可能会推荐我查找.
Id like to get my basics strong, i
d be grateful for any help and suggestions for code you might recommend I look up.
谢谢!
推荐答案
你的问题是关于如何使用日志记录的细节还是关于日志记录异常,我不太清楚,但如果是后者,我会同意 Adam Crossland 的观点log-and-swallow 是一种需要避免的模式.
It's not very clear whether your question is about the specifics of how to use logging or about logging exceptions, but if the latter, I would agree with Adam Crossland that log-and-swallow is a pattern to be avoided.
就日志记录的机制而言,我会提出以下意见:
In terms of the mechanics of logging, I would make the following observations:
- 您不需要将记录器作为实例成员.使用
logger = logging.getLogger(__name__)
在模块级别声明记录器更自然,这也将在子包中按预期工作. - 您的调用 logger.log("message") 无论如何都可能会失败,因为 log 方法将级别作为第一个参数,而不是消息.
- You don't need to have a logger as an instance member. It's more natural to declare loggers at module level using
logger = logging.getLogger(__name__)
, and this will also work as expected in sub-packages. - Your call logger.log("message") would likely fail anyway because the log method has a level as the first argument, rather than a message.
你应该声明处理程序,如果你的使用场景相当简单,你可以在你的 main 方法或 if __name__ == '__main__':
子句中添加例如
You should declare handlers, and if your usage scenario is fairly simple you can do this in your main method or if __name__ == '__main__':
clause by adding for example
logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
然后在您的代码中的其他地方,例如
and then elsewhere in your code, just do for example
import logging
logger = logging.getLogger(__name__)
在要使用日志记录的每个模块的顶部一次,然后
once at the top of each module where you want to use logging, and then
logger.debug('message with %s', 'arguments') # or .info, .warning, .error etc.
在您的代码中需要的地方.
in your code wherever needed.
这篇关于日志机制的区别:API 和应用程序(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!