python - 使用多个模块进行 Python 日志记录的常见/标准做法是什么?

标签 python logging coding-style standards python-2.6

假设我有一个依赖两个模块的脚本:

  • 主要.py
  • 模块1.py
  • 模块2.py

只会执行Main.py,但是在Main的执行过程中,有多次调用Module1.py和Module2.py内部的方法。

更常见的是...

1) 将所有内容记录到 Main.py 的日志中?

2) 将每个操作各自模块的所有内容记录到日志中?

(tl;博士,如果您理解我的问题,则无需继续阅读。否则,这是一个示例):

<小时/>

示例(使用非常缩写的代码):

案例 #1 只有一个日志文件,我们将其称为 Main.log。假设记录器名称没有硬编码(尽管在本例中是这样),所以我应该制作 AnotherMain.py ,例如,所有日志条目都将进入 AnotherMain.log

Main.py:

some_value = Module1.get_value("abc")
some_other_value = Module2.get_value("def")
some_result = some_value + some_other_value
log("main", "some_result evaluated successfully")

Module1.py:

def get_value(key):
   ...
   log("main", "returning value for key from Module1")

Module2.py:

def get_value(key):
   ...
   log("main", "returning value for key from Module2")

这将导致 Main.log 读取:

some_result evaluated successfully
returning value for key from Module1
returning value for key from Module2

案例#2有三个日志文件,每个模块一个:Main.log、Module1.log、Module2.log。

Main.py:

some_value = Module1.get_value("abc")
some_other_value = Module2.get_value("def")
some_result = some_value + some_other_value
log("main", "some_result evaluated successfully")

Module1.py:

def get_value(key):
   ...
   log("Module1", "returning value for key")

Module2.py:

def get_value(key):
   ...
   log("Module2", "returning value for key")

这将产生三个日志,每个日志只有一行仅说明该模块内发生的情况。

我不是在问“你更喜欢哪个”,而是问哪个更标准、更常见?一旦我离开,这会让我的继任者更乐意处理和维持?

最佳答案

最佳实践是使用 logging library ,并将所有内容留给该库。

每个模块都使用自己的记录器:

import logging

log = logging.getLogger(__name__)

# ...
log.warn('Do not fnord the frazzle, faf the frobnir instead')

并在主模块中配置日志记录;您可以配置一个日志文件,或者如果需要,可以将特定模块的输出直接输出到特定文件。

默认情况下,记录器将所有内容传播到根记录器,但是每个模块使用单独的记录器可以让您在将来想要设置更复杂的日志记录配置时更加灵活。

您可以根据需要调整格式并直接记录到其他后端。格式化程序有一个 lot of options要调整生成的消息,请确保包含记录器名称。 configuration options for formatting, filtering and handling几乎是无穷无尽的。

重点是,您拥有多少个日志文件以及这些文件中包含哪些内容是配置的问题。根据您的需求变化调整配置。从简单的事情开始;将所有内容记录到一个文件中,然后从那里开始进行。通过为每个模块提供自己的日志记录对象,您可以单独配置每个记录器,坚持默认值并将所有内容传播到根处理程序。

关于python - 使用多个模块进行 Python 日志记录的常见/标准做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499436/

相关文章:

c# - 如果使用 Enterprise Library,log4net 是否更适合登录?

c# - 返回值样式问题

python - 在Python中使用Beautifulsoup获取html标签中的内部文本

python - 如何运行 CUDA 8.0 中包含的示例文件?

python - 在 PyQt4 QtWebkit 中从网页访问图像

python - 在python多生产者和多消费者线程中,queue.join()可能不可靠吗?

java - 将 logback.xml 转换为 log4j.properties

python |创建一个文件并在每次运行时递增名称

ios - 重构 iOS 代码 : Decreasing the number of lines of code

c# - 如果只需要进行微小的更改,如何在不复制完整方法的情况下实现重载?