这可能是一个开放性的或者棘手的问题,但是我发现在处理异常时越来越多的情况下我不知道最佳的处理方式。
如果你试图使用不存在的文件配置FileHandler,Python 的logging模块会引发IOError。该模块不处理此异常,而是直接引发它。通常情况下,这是由于文件路径不存在(因此文件不存在),所以我们必须创建沿着路径的目录,如果想要处理异常并继续运行。
我希望我的应用程序能够正确地处理这个错误,因为每个用户都问过我们为什么不为他们创建合适的目录。
我决定处理这个问题的方式如下所示。
done = False
while not done:
try:
# Configure logging based on a config file
# if a filehandler's full path to file does not exist, it raises an IOError
logging.config.fileConfig(filename)
except IOError as e:
if e.args[0] == 2 and e.filename:
# If we catch the IOError, we can see if it is a "does not exist" error
# and try to recover by making the directories
print "Most likely the full path to the file does not exist, so we can try and make it"
fp = e.filename[:e.rfind("/")]
# See https://dev59.com/L3VC5IYBdhLWcg3wfxU8 for why I don't just leap
if not os.path.exists(fp):
os.makedirs(fp)
else:
print "Most likely some other error...let's just reraise for now"
raise
else:
done = True
我需要循环(或递归)因为有N个FileHandlers需要配置,因此会发生N个IOErrors并需要对其进行纠正。
这样做是否正确?是否存在更好的、更符合Python规范的方式,我不知道或者可能没有理解到?
fileConfig
,就像你的源代码中一样),还是日志文件的名称(根据你的问题文本 - “尝试使用不存在的文件配置FileHandler”)。我的回答是针对后者的。通常,在指定文件(无论是配置文件还是日志文件)时,有很多需要确保的事情 - 例如,一个文件可能已经存在,但由于权限问题而无法读取或写入。没有一种“一刀切”的解决方案,这就是为什么有时需要自己动手的原因。 - Vinay Sajip