Python 错误日志位置

1 投票
1 回答
11963 浏览
提问于 2025-04-17 21:50

我正在开发一个基于 flask 框架的 Python 应用程序,并使用 .wsgi 来部署它。不过,我对错误日志的位置有点困惑。看起来 Python 的错误和调试信息被放到了不同的日志文件里。

首先,我在 apachevhost 文件中指定了访问日志和错误日志的位置。

<VirtualHost *:myport>
    ...
    CustomLog /homedir/access.log common
    ErrorLog /homedir/error.log
    ...
</VirtualHost>

我还知道有另一个 apache 错误日志,路径是 /var/log/httpd/error_log。我的访问日志打印到了正确的位置,/homedir/access.log

但是,错误日志看起来有点奇怪。像 SyntaxError 这样的 Python 错误和未捕获的异常被记录到了 vhost 文件中指定的日志文件(/homedir/error.log)。但是,任何通过 Python 的 logging 模块生成的日志消息却去了“默认”的错误日志(/var/log/httpd/error_log)。

有没有人能解释一下为什么会这样,以及如何解决这个问题?我希望这两种日志能放到同一个地方。


感谢大家的评论。这是我设置日志记录器的代码。

import logging

# I didn't specify the stream, so it suppose to be stderr
# Don't know why stderr points to apache /var/log/*, rather than my error log

stream_handler = logging.StreamHandler()
formatter = logging.Formatter("%(levelname)s : %(pathname)s:%(lineno)s - %(msg)s")
stream_handler.setFormatter(formatter)

logger = logging.getLogger('foo')
logger.addHandler(stream_handler)
logger.setLevel(logging.DEBUG)

然后,我是这样记录消息的。

import logging
logger = logging.getLogger('foo.bar')

logger.debug('Some debug information')

但是,日志却去了 /var/log/httpd/error_log,而不是我在 apache vhost 文件中指定的日志。

1 个回答

0

你应该使用 flask.logging.default_handler,而不是 logging.StreamHandler()。因为前者会用 request.environ['wsgi.errors'] 来创建输出流,而后者则不会。想了解更多细节,可以参考 这里

如果想获取关于 request.environ['wsgi.errors'] 的更多信息,可以查看 这里

撰写回答