是否有可能在 Python 中实现以下(伪)代码的等价物?
#define DEBUG(topic, msg) LOG_IMPL(Logger.DEBUG, topic, msg)
#define INFO(topic, msg) LOG_IMPL(Logger.INFO, topic, msg)
#define LOG_IMPL(level, topic, msg) if(Logger.level() <= level) { Logger.log(level, topic, msg); }
DEBUG("MyComponent", "What you logging at?")
这里的好处是您不必评估字符串日志消息,例如连接字符串、调用 .format() 等)
更新:
Lazy logger message string evaluation - 这回答了我的问题,所以我将投票关闭这篇文章。
最佳答案
Python 自带电池,还有一个 logging module
是标准库的一部分:
from logging import getLogger
log = getLogger('my.module')
log.debug('Debug level messages')
log.warning('Warning!')
log.info('Informative message')
log.error('Error messages')
log.exception('Use this in an exception handler, the exception will be included automatically')
以上这组方法是log.log(level, msg)
方法的快捷方式,取任意(整数)层级,logging
模块定义DEBUG
、WARNING
等级别。
这些方法支持 python string formatting templates 的惰性求值; 仅当消息的日志级别实际超过正在记录的日志级别时,才会插入额外的参数:
log.warning('Warning message: the %s is missing %i frobnars', systemname, count)
只有当日志消息实际到达处理程序时,上面的消息才会被记录为等价于 'Warning message: the %s is missing %i frobnars' % (systemname, count)
。
关于python - Python 中是否可以使用 C++ 样式的日志记录宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11180865/