[英]What is the correct way of configuring Python's logging.FileHandler?
I wrote a small-ish Python script that handles nightly conversions and archiving of audio data.我编写了一个小型 Python 脚本,用于处理夜间转换和音频数据存档。 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.
由于一路上出现了一些意想不到的问题(不存在的文件、与数据库服务器的不可靠连接等等……),我添加了 Python 自己的日志记录工具来跟踪任何遇到的问题。
The problem is, the log file is created wherever the script is run from (eg 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).问题是,日志文件是在脚本运行的任何地方(例如当前工作目录)创建的,所以我有两个日志文件,一个在我的 homedir(当脚本由 cron 运行时使用)和一个在脚本自己的目录(在调试时使用)。 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'))
...and here is the relevant portion of my logger.conf
: ...这是我的
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.绝对路径确实有效,但我有点不愿意使用它们。
In short, what is the proper way to configure file logging using Python's logger
module (especially the FileHandler)?简而言之,使用 Python 的
logger
模块(尤其是 FileHandler)配置文件日志记录的正确方法是什么? Some real-world examples will suffice.一些现实世界的例子就足够了。
So, apparently I can use Python expressions inside the configuration file:所以,显然我可以在配置文件中使用 Python 表达式:
[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__)
resolves to /usr/lib/python2.7/logging/
on my system, which is probably where the logging module resides). (
os.path.dirname(__file__)
在我的系统上解析为/usr/lib/python2.7/logging/
,这可能是日志模块所在的位置)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.