python - 在 Python 2 中指定自定义日志记录 Linux 文件路径

标签 python linux logging

我正在尝试了解日志文件如何与 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 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

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

关于python - 在 Python 2 中指定自定义日志记录 Linux 文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45983640/

相关文章:

Ruby:将记录器消息发送到字符串变量?

python - 值错误 : "undefined get method !" while evaluating u'action_ship_create()' in Odoo

linux - 以编程方式解锁屏幕(桌面Linux)

linux - 如何使用 BSS var 将字符串移动到寄存器 NASM

c++ - 在简单的 pthread 中运行服务器

java - 在 Eclipse 项目中存储日志文件?

python - Web Scraper 无法从网站获取完整数据

python - (keyError : 'CELERY_BROKER_URL' )

Python 情节 : How to denote ticks on the axes as powers?

c++ - 是否有 C++11 或 Win32 方法来可靠地生成和保存跟踪信息?