正确处理logging.config.fileConfig抛出的IOError?
这可能是一个开放式或尴尬的问题,但我发现自己遇到了越来越多的异常处理问题,我不知道处理它们的“最佳”方法。
如果您尝试使用不存在的文件配置 FileHandler,Python 的日志记录模块会引发 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 http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write#273208 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 个 FileHandler,因此需要针对这种情况引发和纠正 N 个 IOError。
这是执行此操作的正确方法吗?有没有更好、更 Pythonic 的方法,但我不知道或可能不理解?
This may be an open ended or awkward question, but I find myself running into more and more exception handling concerns where I do not know the "best" approach in handling them.
Python's logging module raises an IOError if you try to configure a FileHandler with a file that does not exist. The module does not handle this exception, but simply raises it. Often times, it is that the path to the file does not exist (and therefore the file does not exist), so we must create the directories along the path if we want to handle the exception and continue.
I want my application to properly handle this error, as every user has asked why we don't make the proper directory for them.
The way I have decided to handle this can be seen below.
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 http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write#273208 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
I need to loop (or recurse I suppose) since there is N FileHandlers that need to be configured and therefore N IOErrors that need to be raised and corrected for this scenario.
Is this the proper way to do this? Is there a better, more Pythonic way, that I don't know of or may not understand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是日志记录模块特有的:一般来说,Python 代码不会自动为您创建中间目录;而是会自动为您创建中间目录。您需要使用 os.makedirs() 显式执行此操作,通常如下所示:
您可以用子类替换通过记录提供的标准 FileHandler ,该子类会执行您需要的检查,并且必要时,使用 os.makedirs() 创建日志文件的目录。然后您可以在配置文件中指定此处理程序而不是标准处理程序。
This is not something specific to the logging module: in general, Python code does not automatically create intermediate directories for you automatically; you need to do this explicitly using
os.makedirs()
, typically like this:You can replace the standard
FileHandler
provided by logging with a subclass which does the checks you need and, when necessary, creates the directory for the logging file usingos.makedirs()
. Then you can specify this handler in the config file instead of the standard handler.假设只需要在应用程序执行开始时完成一次,我只需
os.makedirs()
所有需要的目录,而不先检查它们是否存在,甚至等待日志记录模块引发一个错误。如果您在尝试启动记录器时遇到错误,您可以按照您可能已经做过的方式处理它:打印错误,禁用记录器。您仅仅通过尝试创建目录就取得了超出预期的成果。如果用户向您提供了虚假信息,您的情况不会比现在更糟,而且在绝大多数情况下您的情况会更好。Assuming it only needs to be done once at the beginning of your app's execution, I would just
os.makedirs()
all the needed directories without checking for their existence first or even waiting for the logging module to raise an error. If you then you get an error trying to start a logger, you can just handle it the way you likely already did: print an error, disable the logger. You went above and beyond just by trying to create the directory. If the user gave you bogus information, you're no worse off than you are now, and you're better in the vast majority of cases.