如何在Python中记录异常?
我查看了一些选项,发现我可以使用以下代码访问实际的异常详细信息:
import sys
import traceback
try:
1/0
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
Run Code Online (Sandbox Code Playgroud)
我想以某种方式将字符串print_exception()抛出到stdout以便我可以记录它.
我想检查特定后台文件中的错误,但标准错误流由前台程序控制,并且不显示问题中文件中的错误.不过,我可以使用logging模块并将输出写入文件.我想知道如何使用它来记录所有异常,错误及其追溯.
在以下代码中,assert在单元测试之外使用:
import logging
if __name__ == "__main__":
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("info level")
assert 1 == 0
Run Code Online (Sandbox Code Playgroud)
打印如下:
2016-02-16 14:56:58,445 - __main__ - INFO - info level
Traceback (most recent call last):
File "logtest.py", line 7, in <module>
assert 1 == 0
AssertionError
Run Code Online (Sandbox Code Playgroud)
什么是"规范"的方式来使用带时间戳的日志记录格式AssertionError由具有隆起assert(可能无需重写每一个assert代码)?
提出了许多类似的问题,主要涉及asserts单元测试环境......谢谢
在 Python 中记录异常的最正确方法是什么?
有些人只记录e另一个日志属性e.message(但在某些例外情况下可能会丢失)。
一种用于str()捕获异常的描述,但它不包含错误类型,如果没有错误类型,有时就没用。
实际上repr()会返回错误类型和描述,但它并不那么流行(在我看到的项目中)。
还有一个相关问题:这如何影响像 Sentry 这样收集和分组错误/警报的服务。它们还应该包含一些有关具体错误的信息。
因此想再次开启这个讨论:哪种记录异常的方式最好使用?
def foo():
""" Method that can raise various types of exceptions """
1/0 # just for example
try:
foo()
except Exception as e:
logger.exception('Error occurred during execution: %s', e) # 1
logger.exception('Error occurred during execution: %s', e.message) # 2
logger.exception('Error occurred during execution: %s', str(e)) # 3
logger.exception('Error occurred during execution: %s', str(e.message)) # 4
logger.exception('Error occurred during execution: %s', repr(e)) # …Run Code Online (Sandbox Code Playgroud) 我正在使用ThreadPoolExecutorpythonconcurrent.futures并行抓取结果并将结果写入数据库。这样做时,我意识到如果其中一个线程失败,我将无法获得任何信息。我怎样才能正确地知道哪些线程失败以及为什么失败(因此使用“正常”回溯)?下面是一个最小的工作示例。
import logging
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%y-%m-%d %H:%M:%S', level=logging.INFO)
from concurrent.futures import ThreadPoolExecutor
def worker_bee(seed):
# sido is not defined intentionally to break the code
result = seed + sido
return result
# uncomment next line, and you will get the usual traceback
# worker_bee(1)
# ThreadPoolExecutor will not provide any traceback
logging.info('submitting all jobs to the queue')
with ThreadPoolExecutor(max_workers=4) as executor:
for seed in range(0,10):
executor.submit(worker_bee, seed)
logging.info(f'submitted, waiting for threads to finish')
Run Code Online (Sandbox Code Playgroud)
如果我在内部导入日志记录 …
我一直在搜索互联网、Python 的官方文档和 StackOverflow 已经有一段时间了,但似乎找不到正确的答案。
我正在关注 Python 的官方 HOWTO 日志记录 - 我的记录器如下所示:
import os, logging
os.chdir("C:/Users/kerfuffle/Desktop/logtest")
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("logging.log")
fh.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)
logger.debug("debug!")
logger.info("info!")
logger.warning("warning!")
Run Code Online (Sandbox Code Playgroud)
代码的最后 3 行工作正常,我们还通过 StreamHandler 获得了正确的输出。
logging.log - 文件:
2020-05-27 15:41:59,586 - INFO - info!
2020-05-27 15:41:59,586 - WARNING - warning!
Run Code Online (Sandbox Code Playgroud)
控制台输出:
2020-05-27 15:41:59,584 - DEBUG - debug!
2020-05-27 15:41:59,586 - INFO - info!
2020-05-27 15:41:59,586 - WARNING - warning! …Run Code Online (Sandbox Code Playgroud) 我希望我的程序将每个警告写入 .txt 文件中。有没有办法在不使用 catch_warnings 的情况下做到这一点?