python logging:如何确保创建日志文件目录? [英] python logging: how to ensure logfile directory is created?

查看:1617
本文介绍了python logging:如何确保创建日志文件目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 mechanisms which in my case is a section of a YAML file that the end user can edit to specify how logging behaves.)

是否可以通过创建日志来获取日志框架以确保目录存在?因为日志文件名的确切路径嵌入在最终用户指定的配置信息中,因此对于我来说,作为应用程序编写者来解析此信息以确定应创建哪个目录对我来说并不难.

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.

如果最终用户指定"foo/bar/baz.log",我想确保已创建foo/bar目录.

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

注意:这与推荐答案

子类(或您使用的任何处理程序)在初始化期间调用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)

这篇关于python logging:如何确保创建日志文件目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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