简体   繁体   English

如何记录错误?

[英]How do I log errors?

Ultimately i'm trying to write a custom logging module to log the events of some unmanned daily scripts, and currently i'm looking at how to log exceptions.最终,我正在尝试编写一个自定义日志记录模块来记录一些无人日常脚本的事件,目前我正在研究如何记录异常。

Several other SO questions have suggested replacing sys.excepthook with a function to achieve this, but I couldn't get this to work as intended inside my module so now i'm just trying to get a basic example working so I can start to understand what's happening here.其他几个 SO 问题建议用 function 替换 sys.excepthook 来实现这一点,但我无法让它在我的模块中按预期工作,所以现在我只是想让一个基本示例正常工作,这样我就可以开始理解了这里发生了什么事。

in python, how ensure any exceptions are logged with logger? 在 python 中,如何确保使用记录器记录任何异常?

The above question outlines some code they've used to achieve this which is similar/identical to acceptable answers in other SO questions, but none seem to work for me.上面的问题概述了他们用来实现这一目标的一些代码,这些代码与其他 SO 问题中可接受的答案相似/相同,但似乎没有一个对我有用。

Here is my code:这是我的代码:

import logging
import sys


logger = logging.getLogger('myapp logger')
logger.setLevel(logging.INFO)
file_log_handler = logging.FileHandler('myapp.log')
logger.addHandler(file_log_handler)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
logger.addHandler(file_log_handler)


def _excepthook(exctype, exc, tb):
    logger.error("An unhandled exception occurred.", exc_info=(exctype, exc, tb))

sys.excepthook = _excepthook


logger.debug("Hello")
5/0 # error
logger.debug("what")

I'm expecting this to print the details of the ZeroDivisionError to 'myapp.log' but when running from within VS Code, the ZeroDivisionError exception is raised as normal and nothing is printed to 'myapp.log'.我希望这会将 ZeroDivisionError 的详细信息打印到“myapp.log”,但是当从 VS Code 中运行时,ZeroDivisionError 异常会正常引发,并且不会将任何内容打印到“myapp.log”。

Does anyone know where i'm going wrong or how I should be thinking about/approaching this?有谁知道我哪里出错了或者我应该如何考虑/解决这个问题?

A super simple example of replacing sys.excepthook to do anything other than its default behavior would be greatly appreciated.将不胜感激替换 sys.excepthook 以执行其默认行为以外的任何操作的超级简单示例。

I was trying to test this out in Jupyter Notebook and had the same problem.我试图在 Jupyter Notebook 中对此进行测试并且遇到了同样的问题。 Can't override sys.excepthook there or in VS Code, it appears.无法在此处或在 VS Code 中覆盖 sys.excepthook,它会出现。

Googling a little further, I found this SO thread, which explains that IPython replaces sys.excepthook every time you execute a line of code.进一步谷歌搜索,我发现了这个SO 线程,它解释了每次执行一行代码时 IPython 都会替换 sys.excepthook。

This could perhaps be the source of your problem, if your default python interpreter on your system is based on IPython.如果您系统上的默认 python 解释器基于 IPython,这可能是您问题的根源。 In that case, you could try pointing VS Code to the path of an alternate interpreter under File >> Preference >> Settings >> Extensions >> Python >> Default Interpreter Path in VS Code.在这种情况下,您可以尝试在文件 >> 首选项 >> 设置 >> 扩展 >> Python >> VS Code 中的默认解释器路径下将 VS Code 指向备用解释器的路径。

在此处输入图像描述

Also, note that your logger.debug() commands won't write to your log file unless you set the logger level to "DEBUG", because "DEBUG" is at a lower level than "INFO" :另外,请注意,除非您将记录器级别设置为“DEBUG”,否则您的 logger.debug() 命令不会写入日志文件,因为“DEBUG”的级别低于“INFO”
在此处输入图像描述

-----------UPDATE----------------- - - - - - -更新 - - - - - - - - -

On that SO thread I referenced above, further down there is an answer from "Michał Jabłoński", that might work for you, if you are using an IPython interpreter.在我上面引用的那个 SO 线程上,如果你使用的是 IPython 解释器,那么下面有一个来自“Michał Jabłoński”的答案,它可能对你有用。 It worked for me in Jupyter Notebook.它在 Jupyter Notebook 中对我有用。
This worked for me:这对我有用:

import logging
import sys
from IPython import get_ipython
ip = get_ipython()


logger = logging.getLogger('myapp logger')
logger.setLevel(logging.DEBUG)
file_log_handler = logging.FileHandler('myapp.log')
logger.addHandler(file_log_handler)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
logger.addHandler(file_log_handler)


def exception_handler(self, etype, evalue, tb, tb_offset=None):
    logger.error("An unhandled exception occurred.", exc_info=(etype, evalue, tb))

ip.set_custom_exc((Exception,), exception_handler)


logger.debug("Hello")
5/0 # error
logger.debug("what")

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

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