怎么让 logging formatter 显示报错的函数的行数
时间: 2023-11-22 11:52:45 浏览: 44
可以使用 `% (lineno)d` 占位符来显示报错的函数的行数,示例代码如下:
```python
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(lineno)d',
level=logging.DEBUG)
def error_function():
x = 1 / 0
try:
error_function()
except Exception as e:
logging.error("An error occurred", exc_info=True)
```
在这个例子中,我们使用了 `exc_info=True` 参数来将异常信息添加到日志中,同时使用了占位符 `% (lineno)d` 来显示报错的函数的行数。当运行上述代码时,将得到类似于以下输出:
```
2021-10-12 14:16:26,226 - root - ERROR - An error occurred - 6
Traceback (most recent call last):
File "<ipython-input-2-7d5b0c326e7e>", line 12, in <module>
error_function()
File "<ipython-input-2-7d5b0c326e7e>", line 8, in error_function
x = 1 / 0
ZeroDivisionError: division by zero
```
可以看到,输出中包含了报错的函数所在行数。