【问题标题】:Save log files in the user home directory将日志文件保存在用户主目录中
【发布时间】:2016-11-06 05:14:24
【问题描述】:

我有一个 logging.conf [1] 文件来配置我的 python 应用程序中的日志记录。

...
[handler_file_log_handler]
class=logging.handlers.TimedRotatingFileHandler
level=INFO
formatter=simple
args=('/var/log/myapp/myapp.log',)

如您所见,我将日志文件存储在 /var/log/myapp 目录中。

我想要将它存储在用户(管理应用程序的用户)主目录(/home/myuser/.myapp/log)中。所以,我的问题是:

我应该在我的 logging.conf 中配置什么以便能够将我的 python 应用程序的日志文件保存在用户主目录中?

[1] - https://docs.python.org/2.6/library/logging.html#configuring-logging

【问题讨论】:

标签: python logging


【解决方案1】:

是的,您可以将任何 Python 表达式作为参数传递!包括找到用户家的!

args=(f'{os.path.expanduser("~")}/myapp.log',)

对于 Python

args=(os.path.expanduser("~") + '/myapp.log',)

为了完整起见,这里是一个最小的例子(用 3.5 和 3.9 测试):

logging.conf

[loggers]
keys=root

[handlers]
keys=fileLogHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileLogHandler

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[handler_fileLogHandler]
class=logging.handlers.TimedRotatingFileHandler
formatter=simpleFormatter
args=(os.path.expanduser("~") + '/myapp.log',)

ma​​in.py

import logging
import logging.config

logging.config.fileConfig('logging.conf')
log = logging.getLogger(__name__)
log.info('Testo')

补充说明: 我认为将 ~/myapp.log 作为路径传递会起作用,并让操作系统负责扩展,这实际上在 Python 的大多数地方都有效。但莫名其妙地这在 logging.conf 文件中不起作用!

args=('~/myapp.log',)

FileNotFoundError: [Errno 2] No such file or directory: 
    '/path/to/this/python/project/~/myapp.log'  # ???

【讨论】:

    【解决方案2】:

    可以使用以下方法找到用户的主目录(在任何操作系统上):

    os.path.expanduser("~")
    

    【讨论】:

    • 没错。但是,该指令在 logging.conf 文件中有效吗? Python 会在 .conf 文件中翻译该指令吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2014-07-17
    相关资源
    最近更新 更多