代码之家  ›  专栏  ›  技术社区  ›  max

python中的日志文件名存储在哪里?

  •  4
  • max  · 技术社区  · 14 年前

    我有一个Python程序,它由几个模块组成。“main”模块创建一个文件变量 log_file

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

    那么,我应该把 日志文件

    编辑:

    下面是@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)
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   pyfunc    14 年前

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

    http://docs.python.org/library/logging.html

        2
  •  2
  •   Terrel Shumway    14 年前

    将“global”变量放入“settings”模块。

    设置.py

    log_file = "/path/to/file"
    

    import settings
    import logging
    logging.basicConfig(filename=settings.log_file,level=logging.DEBUG)
    
    logging.debug("This should go to the log file")
    

    其他模块.py

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

    logging module 可能会解决您当前的问题和许多其他问题,除了日志文件名之外,设置模块模式对许多其他事情都很有用。Django使用它来配置几乎所有的东西。