日志机制的不同:API和应用程序(python)
我目前正在编写一个API和一个使用该API的应用程序。有人建议我应该使用应用程序中的处理程序执行日志记录,并使用“logger”对象从API进行日志记录 根据我收到的上述建议,以下实施是否正确日志机制的不同:API和应用程序(python),python,api,logging,Python,Api,Logging,我目前正在编写一个API和一个使用该API的应用程序。有人建议我应该使用应用程序中的处理程序执行日志记录,并使用“logger”对象从API进行日志记录 根据我收到的上述建议,以下实施是否正确 class test: def __init__(self, verbose): self.logger = logging.getLogger("test") self.logger.setLevel(verbose) def do_something(
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")
我d想强化我的基础知识,我
d非常感谢您对我查找的代码的任何帮助和建议
Thnkx 您所考虑的模式的危险在于,您可能最终通过将异常放入日志中来有效地隐藏异常。许多异常确实会使程序崩溃,因为它们代表了一个需要修复的问题。通常,能够使用调试器单步执行代码以找出异常的原因更为有用
如果存在异常表示不影响应用程序稳定性或其行为正确性的预期条件的情况,则只需在日志中写入注释即可。但是要非常非常小心如何使用它。你的问题不是很清楚是关于如何使用日志的细节还是关于日志异常,但是如果是后者,我同意Adam Crossland的观点,日志和吞咽是一种需要避免的模式 关于测井机理,我将提出以下观察结果:
logger=logging.getLogger(\uuuu name\uuuuu)
在模块级声明记录器更为自然,这也将在子包中按预期工作如果
子句中通过添加例如
logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
import logging
logger = logging.getLogger(__name__)
然后在代码的其他地方,例如
logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
import logging
logger = logging.getLogger(__name__)
在要使用日志记录的每个模块的顶部显示一次,然后
logger.debug('message with %s', 'arguments') # or .info, .warning, .error etc.
在需要的地方输入代码。我通常会执行以下操作:
import logging
import logging.config
logging.config.fileConfig('log.congig')
# for one line log records
G_LOG = logging.getLogger(__name__)
# for records with stacktraces
ST_LOG = logging.getLogger('stacktrace.' + __name__)
try:
# some code
G_LOG.info('some message %s %s', param1, param2)
except (StandardError,):
message = 'some message'
G_LOG.error(message)
# exc_info appends stacktrace to the log message
ST_LOG.error(message, exc_info=True)
配置文件的格式可以在中看到。我喜欢这个问题,是否有一个教程可以确切地说明在使用日志记录时应该遵循什么样的模式?