【问题标题】:where to store a log file name in python?在 python 中的哪里存储日志文件名?
【发布时间】:2010-11-03 19:04:38
【问题描述】:

我有一个由多个模块组成的 Python 程序。 “main”模块创建一个文件变量log_file 用于记录输出;所有其他模块也需要写入该文件。

但是,我不想将“主”模块导入其他模块,因为这将是一个非常奇怪的依赖项(更不用说它甚至可能由于循环依赖项而无法工作)。

那么,我应该将log_file 变量存储在哪里?

编辑:

按照@pyfunc 的回答——这样可以吗:

--- config.py ---
# does not mention log_file
# unless it's required for syntax reasons; in which case log_file = None
# ...

--- main.py ---
from datetime import datetime
import config.py
log_filename = str(datetime.now()) + '.txt'
config.log_file = open(log_filename, 'w')
# ...

--- another_module.py ---
import config.py
# ...
config.log_file.write(some_stuff)

【问题讨论】:

  • 这个问题似乎没有任何特定于 py3k 的内容。
  • 我建议使用带有配置文件的日志记录包而不是自定义解决方案。
  • 我只是打印输出,而不是错误。我想我仍然可以使用 logging 包......虽然我觉得这有点矫枉过正,我只需要将内容打印到文件中。

标签: python module python-3.x


【解决方案1】:

将“全局”变量放在“设置”模块中。

settings.py

log_file = "/path/to/file"

main.py

import settings
import logging
logging.basicConfig(filename=settings.log_file,level=logging.DEBUG)

logging.debug("This should go to the log file")

other_module.py

import logging
logging.debug("This is a message from another place.")

虽然logging module 可以解决您的直接问题和许多其他问题,但设置模块模式对于日志文件名之外的许多其他事情很有用。 Django 使用它来配置几乎所有内容。

【讨论】:

  • 这就是我正在考虑做的事情(在我上面编辑的代码中的 config.py 中),但我认为我需要在 main.py 中分配文件名,因为它取决于脚本的时间叫做。 Config.py 会被多次导入,所以我不想一直更改文件名。
  • 在您的示例中,log_file 不必是全局变量,因为日志模块将接管。但我理解这个想法。
【解决方案2】:

一种方法是将所有代码放入另一个模块中,以便您可以将其导入主文件和其他模块中。

希望您已查看:http://docs.python.org/library/logging.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2014-03-19
    • 1970-01-01
    相关资源
    最近更新 更多