【问题标题】:Specifying a custom logging Linux filepath in Python 2在 Python 2 中指定自定义日志记录 Linux 文件路径
【发布时间】:2017-08-31 14:13:38
【问题描述】:

我正在尝试了解日志文件如何与Python 2 logging module 一起使用。

我知道我可以使用以下方式将日志输出保存到文本文件中:

logging.basicConfig(filename='example.log',level=logging.DEBUG)

从以下文档中我不清楚:

  1. 绝对filename路径是否有效
  2. 指定相对路径的正确语法(假设../example.log有效)。

如果我从/home/bob 执行此脚本,如何指定我希望将日志文件保存到/tmp 目录而不是使用绝对路径和相对路径?

logging.basicConfig(filename='../../tmp/example.log') 有效吗?

同样,logging.basicConfig(filename='/tmp/example.log') 有效吗?

【问题讨论】:

    标签: python linux logging


    【解决方案1】:

    当只说明文件名时,它将被写入当前目录。 使用 Python IDLE 可以检查如下

    >>> import logging
    >>> logging.basicConfig(filename='relative.log')
    >>> logging.info('test')
    
    C:\Python27\relative.log
    

    我的工作目录是 Python27,我有一个名为 relative.log 的文件,其中包含我记录的消息。

    当您将文件位置更改为../relative.log 时,我在Python27 的父目录中获得了一个新文件。所以相对路径确实适用于日志记录:

    >>> import logging
    >>> logging.basicConfig(filename='../relative.log')
    >>> logging.info('test123')
    
    C:\relative.log
    

    并且logging模块也支持绝对路径

    >>> logging.basicConfig(filename=r'c:\abs_path.log')
    >>> logging.info('test')
    
    C:\abs_path.log
    

    使用绝对路径总是更好,因为显式优于隐式

    【讨论】:

    • 谢谢 - 这无疑是一个愚蠢的问题。我已经验证绝对路径也适用于 Linux 环境。
    • 会的
    【解决方案2】:

    它们都是有效的。但是相对路径(带有..)会根据您运行时所在的目录选择不同的文件。

    因此,当您在/home/user/projects/python 中运行logger.py 并且文件名为../log.txt 时,该文件将保存在/home/user/projects 中。另一方面,当您在/home/user 中运行脚本时,log.txt 将保存在/home/ 中。

    绝对路径始终有效且更可靠。如果您想要当前目录中的文件,我推荐这种方法:

    basedir = os.path.abspath(os.path.dirname(__file__))
    filename = os.path.join(basedir, 'file.txt')
    

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      相关资源
      最近更新 更多