简体   繁体   English

配置python logger在无法写入文件时引发异常

[英]configuring python logger to throw exception when it can't write to file

I'm trying to use python's logging class, and encountering an issue where nothing gets written to the log file. 我正在尝试使用python的日志记录类,并且遇到了什么都没有写入日志文件的问题。 According to the python documentation , the general rule is the class won't tell you about a problem while executing: 根据python文档 ,一般规则是该类在执行时不会告诉您问题:

"The logging package is designed to swallow exceptions which occur while logging in production" “日志记录程序包旨在吞并在生产中记录时发生的异常”

But I'm interested to understand any issues logging is encountering. 但我有兴趣了解logging遇到的任何问题。 The doc goes on to mention you can set a module level variable, raiseExceptions to see some more verbosity. 该文档继续提到您可以设置模块级别的变量,raiseExceptions来查看更多详细信息。

My question is, how do I set that and/or is there a more direct way to go about debugging this sort of issue? 我的问题是,我该如何设置和/或是否有更直接的方法来调试此类问题?

For reference, here is my implementation of logging (python 2.7): 作为参考,这是我的logging实现(python 2.7):

numeric_log_level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(numeric_log_level, int):
     raise ValueError('Invalid log level: %s' % args.loglevel)
logging.basicConfig\
    (filename=args.logfile, level=numeric_log_level, format="%(asctime)s - [client] - %(levelname)s - %(message)s")

The documentation you linked to goes on to mention it's already enabled: 您链接到的文档继续提到它已经启用:

The default value of raiseExceptions is True. raiseExceptions的默认值为True。

Essentially exceptions for misconfigured logging will by default be printed the stderr . 本质上,错误配置的日志记录的例外情况默认情况下将在stderr打印。 So if you want to see any of these problems, watch the output of your app if you are running it in a terminal. 因此,如果您要查看这些问题中的任何一个,请在终端中运行应用程序时查看其输出。

If you are running it as a service or daemon, make sure you direct the stderr to a file. 如果将其作为服务或守护程序运行,请确保将stderr定向到文件。 There are many different ways to do this depending on how you are daemonizing your script, but one common way is 有多种方法可以执行此操作,具体取决于您如何守护脚本,但是一种常见的方法是

python script.py 2> /path/to/log_exceptions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM