python日志记录:如何确保创建日志文件目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20666764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:59:07  来源:igfitidea点击:

python logging: how to ensure logfile directory is created?

pythonlogging

提问by Jason S

I would like to use python's logging framework in my application, and I'd like to allow the end user of my application to specify the log file. (Via the Python logging framework's configuration mechanismswhich in my case is a section of a YAML file that the end user can edit to specify how logging behaves.)

我想在我的应用程序中使用 python 的日志框架,并且我想允许我的应用程序的最终用户指定日志文件。(通过 Python 日志框架的配置机制,在我的情况下,它是最终用户可以编辑的 YAML 文件的一部分,以指定日志记录的行为方式。)

Is there a way to get the logging framework to ensure that a directory exists by creating it?Because the exact path to the logging filename is embedded in the configuration information specified by the end user, it is nontrivial for me as the application writer to parse this information to determine which directory should be created.

有没有办法让日志框架通过创建目录来确保目录存在?因为日志文件名的确切路径嵌入在最终用户指定的配置信息中,所以作为应用程序编写者,解析此信息以确定应该创建哪个目录对我来说非常重要。

If the end user specifies "foo/bar/baz.log", I would like to make sure that the foo/bar directory is created.

如果最终用户指定“foo/bar/baz.log”,我想确保创建了 foo/bar 目录。

Note: This is the Python equivalent of this SO question about Java logging.

注意:这是关于 Java logging这个 SO 问题的 Python 等价物。

采纳答案by unutbu

Subclass FileHandler(or whatever handler you are using) to call mkdir_pduring initialization:

在初始化期间FileHandler调用的子类(或您使用的任何处理程序)mkdir_p

import logging
import os
import errno

def mkdir_p(path):
    """http://stackoverflow.com/a/600612/190597 (tzot)"""
    try:
        os.makedirs(path, exist_ok=True)  # Python>3.2
    except TypeError:
        try:
            os.makedirs(path)
        except OSError as exc: # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else: raise

class MakeFileHandler(logging.FileHandler):
    def __init__(self, filename, mode='a', encoding=None, delay=0):            
        mkdir_p(os.path.dirname(filename))
        logging.FileHandler.__init__(self, filename, mode, encoding, delay)