配置Python的logging.FileHandler的正确方法是什么? [英] What is the correct way of configuring Python's logging.FileHandler?

查看:1968
本文介绍了配置Python的logging.FileHandler的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个很小的Python脚本,该脚本处理每晚的转换和音频数据的归档.由于在执行过程中出现了一些意外的问题(文件不存在,与数据库服务器的连接不可靠等等),我添加了Python自己的日志记录工具来跟踪遇到的任何问题.

I wrote a small-ish Python script that handles nightly conversions and archiving of audio data. Since there have been some unexpected problems along the way (non-existing files, unreliable connection to the database server and so on...), I added Python's own logging facility to keep track of any encountered problems.

问题是,无论在哪里运行脚本(例如当前工作目录),都将创建日志文件,所以我有两个日志文件,一个在我的homedir中(当cron运行脚本时使用),另一个在脚本自己的目录(在调试时使用).我更希望将日志文件和配置文件与脚本保存在同一目录中.

The problem is, the log file is created wherever the script is run from (e.g. current working directory), so I have two logfiles, one in my homedir (which is used when the script is run by cron) and one in the script's own directory (used when I debug it). I'd much prefer keeping the logfile and configuration file in the same directory as the script.

我在这里加载记录器的配置:

I'm loading logger's configuration here:

logging.config.fileConfig(os.path.join(sys.path[0], 'logger.conf'))

...这是我的logger.conf的相关部分:

...and here is the relevant portion of my logger.conf:

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('echi_export.log', 'a',)

绝对路径有效,但我还是不太愿意使用它们.

Absolute paths do work, I'm a bit reluctant to use them though.

简而言之,使用Python的logger模块(尤其是FileHandler)配置文件记录的正确方法是什么?一些真实的例子就足够了.

In short, what is the proper way to configure file logging using Python's logger module (especially the FileHandler)? Some real-world examples will suffice.

推荐答案

因此,很明显,我可以在配置文件中使用Python表达式:

So, apparently I can use Python expressions inside the configuration file:

[handler_fileHandler]
  <snip>
args=(os.path.join(sys.path[0],'echi_export.log'), 'a',)

这将导致在脚本所在的目录中创建日志文件.

This results in the logfile being created in the same directory the script resides in.

(在我的系统上,os.path.dirname(__file__)解析为/usr/lib/python2.7/logging/,这可能是日志记录模块所在的位置).

(os.path.dirname(__file__) resolves to /usr/lib/python2.7/logging/ on my system, which is probably where the logging module resides).

这篇关于配置Python的logging.FileHandler的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆