【发布时间】:2010-06-08 05:47:47
【问题描述】:
TL;DR 版本: 在 Python 项目的 C++ 位中,您使用什么来进行可配置(最好是捕获)日志记录?详情如下。
假设您有一些已编译的.so 模块可能需要进行一些错误检查并警告用户(部分)不正确的数据。目前我有一个非常简单的设置,我使用来自 Python 代码的logging 框架和来自 C/C++ 的log4cxx 库。 log4cxx 日志级别在文件 (log4cxx.properties) 中定义,目前已修复,我正在考虑如何使其更灵活。我看到的几个选择:
-
控制它的一种方法是进行模块范围的配置调用。
# foo/__init__.py import sys from _foo import import bar, baz, configure_log configure_log(sys.stdout, WARNING) # tests/test_foo.py def test_foo(): # Maybe a custom context to change the logfile for # the module and restore it at the end. with CaptureLog(foo) as log: assert foo.bar() == 5 assert log.read() == "124.24 - foo - INFO - Bar returning 5" -
让每个编译后的函数都接受可选的日志参数。
# foo.c int bar(PyObject* x, PyObject* logfile, PyObject* loglevel) { LoggerPtr logger = default_logger("foo"); if (logfile != Py_None) logger = file_logger(logfile, loglevel); ... } # tests/test_foo.py def test_foo(): with TemporaryFile() as logfile: assert foo.bar(logfile=logfile, loglevel=DEBUG) == 5 assert logfile.read() == "124.24 - foo - INFO - Bar returning 5" 其他方式?
第二个似乎更干净一些,但它需要更改函数签名(或使用 kwargs 并解析它们)。第一个是.. 可能有点尴尬,但一次性设置了整个模块并从每个单独的函数中删除了逻辑。
您对此有何看法?我也很喜欢替代解决方案。
谢谢,
【问题讨论】:
标签: python unit-testing logging log4cxx