<p>让我们创建一个非常复杂的stacktrace,以演示我们得到了完整的stacktrace:</p>
<pre><code>def raise_error():
raise RuntimeError('something bad happened!')
def do_something_that_might_error():
raise_error()
</code></pre>
<h2>记录完整的stacktrace</h2>
<p>最佳实践是为模块设置记录器。它将知道模块的名称并能够更改级别(以及其他属性,如处理程序)</p>
<pre><code>import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
</code></pre>
<p>我们可以使用此记录器获取错误:</p>
<pre><code>try:
do_something_that_might_error()
except Exception as error:
logger.exception(error)
</code></pre>
<p>哪些日志:</p>
<pre><code>ERROR:__main__:something bad happened!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
</code></pre>
<p>因此,我们得到的输出与出现错误时相同:</p>
<pre><code>>>> do_something_that_might_error()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
</code></pre>
<h2>只得到绳子</h2>
<p>如果您真的只需要字符串,请改用<code>traceback.format_exc</code>函数,演示如何在此处记录字符串:</p>
<pre><code>import traceback
try:
do_something_that_might_error()
except Exception as error:
just_the_string = traceback.format_exc()
logger.debug(just_the_string)
</code></pre>
<p>哪些日志:</p>
<pre><code>DEBUG:__main__:Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
</code></pre>