所以代替:Traceback (most recent call last): File "/home/math/Desktop/test.py", line 32, in <module> adfNameError: name 'adf' is not defined类似{"message": "Traceback (most recent call last):\n File \"/home/math/Desktop/test.py\", line 32, in <module>\n adf\n NameError: name 'adf' is not defined", "lineno": 35, "pathname": "/home/math/Desktop/test.py"}甚至还可以使用JSON格式的字符串.我能想到的唯一方法是巨大的try-except块.宠物小精灵风格.有更好的解决方案吗?解决方案您可以使用 sys.excepthook .每当脚本中发生异常时,就会调用它.import loggingimport sysimport tracebackdef exception_logging(exctype, value, tb): """ Log exception by using the root logger. Parameters ---------- exctype : type value : NameError tb : traceback """ write_val = {'exception_type': str(exctype), 'message': str(traceback.format_tb(tb, 10))} logging.exception(str(write_val))然后,您必须在脚本中覆盖sys.excepthook的值.sys.excepthook = exception_logging现在,每当发生异常时,它将使用您的记录器处理程序记录下来.注意:运行此操作前请不要忘记设置记录器I am using AWS and use AWS cloudwatch to view logs. While things should not break on AWS, they could. I just had such a case. Then I searched for Traceback and just got the linesTraceback (most recent call last):without the actual traceback. I have a working structured logging setup (see other question) and I would like to get tracebacks in a similar way.So instead of:Traceback (most recent call last): File "/home/math/Desktop/test.py", line 32, in <module> adfNameError: name 'adf' is not definedsomething like{"message": "Traceback (most recent call last):\n File \"/home/math/Desktop/test.py\", line 32, in <module>\n adf\n NameError: name 'adf' is not defined", "lineno": 35, "pathname": "/home/math/Desktop/test.py"}or even better also with the string in a JSON format.The only way to achieve this I can think of is a giant try-except block. Pokemon-style. Is there a better solution? 解决方案 You can use sys.excepthook. It is invoked whenever an exception occurs in your script.import loggingimport sysimport tracebackdef exception_logging(exctype, value, tb): """ Log exception by using the root logger. Parameters ---------- exctype : type value : NameError tb : traceback """ write_val = {'exception_type': str(exctype), 'message': str(traceback.format_tb(tb, 10))} logging.exception(str(write_val))Then in your script you have to override the value of sys.excepthook.sys.excepthook = exception_loggingNow whenever an exception occurs it will be logged with your logger handler.Note: Don't forget to setup logger before running this 这篇关于我可以在一行中/通过日志记录来使Python输出异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
06-04 05:56
查看更多