python - 使用 Python 记录器记录到文件和标准错误

标签 python logging python-2.7

我正在尝试向使用标准 Python (2.7) 日志库的项目添加模块。我想要实现的是:

  • 任何等于或比 WARNING 更差的内容都会发送到主程序(在我的控制范围之外)配置日志记录的任何地方(通常是 stderr)
  • 其他所有内容(主要是调试消息)都记录在日志文件中

请注意,这里的关键问题是我不想修改全局日志记录设置,因为它们由主应用程序控制。否则我会使用此处的示例:

http://docs.python.org/2/howto/logging-cookbook.html#logging-to-multiple-destinations

我已经试过了:

logger = logging.getLogger('my_module')
logger.setLevel(logging.WARNING)
fh = logging.FileHandler('my_module.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)

但后来我的文件中只收到警告消息。

如果我将上面的行替换为:

logger.setLevel(logging.DEBUG)

然后我在 stderr 和我的文件中都得到了调试消息。

然后我试了一下:

logger = logging.getLogger('my_module')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.NullHandler())
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
logger.addHandler(console)
fh = logging.FileHandler('my_module.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)

但还是没有运气。

那么我是否可以在不必调用 basicConfig() 或任何其他影响全局日志基础结构的情况下实现这一点?如果可能的话,我只想在这里修改我自己的模块。

谢谢!

最佳答案

  • Anything equal or worse than WARNING goes to wherever the main program (outside of my control) has configured the logging to go (usually stderr)
  • Everything else (debug messages mainly) go to a log file

如果不对祖先的处理程序设置 WARNING 级别,则无法使用单个记录器执行此操作。来自 the docs :

Logger.propagate

If this evaluates to true, logging messages are passed by this logger and by its child loggers to the handlers of higher level (ancestor) loggers. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.


what do you suggest a module can do in this situation?

一般来说,除了为记录器设置警告级别和添加 NullHandler() 之外,库代码根本不应该配置日志记录。

如果您希望主应用程序以一种简单的方式为您提供调试信息,那么请定义一个函数来为您的库配置 DEBUG 级别的日志记录。


I don't want the library to be DEBUG except for the file, where I would like to see everything.

如果你不能控制主程序,那么你不应该创建调试文件作为使用 your_module 的副作用,除非明确要求这样做:

import your_module # in the main application

your_module.get_logger().log_to_file(filename) # without this line your module
                                               # shouldn't create debug files
...
your_module.some_function()

I am not sure how this logger hierarchy works: the logger I created is a child of the root logger that the app configured?

'' 是根记录器。 'a.b''a' 记录器的子项。

关于python - 使用 Python 记录器记录到文件和标准错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14363127/

相关文章:

python - 将列转换为 Pandas 数据框中的表头

python - 使用 matplotlib *没有* TCL

logging - 如何根据 mod_userdir 的用户拥有单独的 Apache2 日志文件?

spring-boot - 在 JsonLayout 中添加 MDC 变量 - log4j2

java - 使用 Java.util 的 Logger 和 FileHandler 类时,几秒钟后日志文件未更新

python-2.7 - 如何从数据库中获取数据并在 kivy+python 中显示在表中

python - .remove 不删除给定的字符串

python - 如何在 Python 中找出字符串中的中文或日文字符?

python - 在 Django 中测试空/空字符串

python - 优化 Python 2.7 中的过滤列表