python - Python 中是否可以使用 C++ 样式的日志记录宏?

标签 python c++ logging macros

是否有可能在 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模块定义DEBUGWARNING等级别。

这些方法支持 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/

相关文章:

python - 为什么我的 Flask 应用程序应该在应用程序的父目录中包含数据库和数据库存储库?

c++ - 我的代码如何在编译时做一件事,而在运行时做另一件事?

c++ - namespace 检测

python - gnuplot vs Matplotlib

java - Wildfly 17.0.1.Final 上的部署问题

python - 使用 python requests 模块上传文件

Python:脚本中的内存问题

php - 如何将文件内容实时流式传输到浏览器

python - 如何加快 Python 中 simplejson 的速度?

c++ - 使用谓词根据大小排序