怎么让 logging 模块 显示 调用的文件名字和行号
时间: 2023-11-28 10:48:46 浏览: 33
可以通过在 logging.basicConfig() 函数中设置参数来指定输出格式。下面的代码演示了如何在输出信息中包含文件名和行号:
```python
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(filename)s - %(lineno)d',
level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("This is an info message")
```
其中,format 参数指定了输出格式。`%(filename)s` 和 `%(lineno)d` 分别表示文件名和行号。通过这种方式,当调用 logger 对象的 info() 方法时,输出信息中将包含文件名和行号。
相关问题
怎么让logging显示报错的时候的行号而不是显示引用的函数的行号
在 Python 中,可以使用 `logging` 模块的 `Logger` 对象的 `exception` 方法输出异常信息,并自动添加异常发生的文件名和行号信息。示例如下:
```python
import logging
try:
# some code that may raise an exception
raise ValueError("something went wrong")
except Exception as e:
logging.getLogger().exception(e)
```
当程序执行到 `logging.getLogger().exception(e)` 时,如果发生了异常,`exception` 方法会自动输出异常信息和发生异常的文件名和行号信息,例如:
```
ERROR:root:something went wrong
Traceback (most recent call last):
File "example.py", line 5, in <module>
raise ValueError("something went wrong")
ValueError: something went wrong
```
注意,使用 `exception` 方法需要将日志级别设置为 `ERROR` 或更高级别,否则不会输出异常信息。
多个Python文件调用logging模块
多个Python文件调用logging模块可以通过以下步骤实现:
1. 在每个Python文件中导入logging模块:
```python
import logging
```
2. 在每个Python文件中设置logging配置,如日志级别、输出格式等:
```python
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
```
3. 在每个Python文件中使用logging模块记录日志:
```python
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
```
4. 如果需要将日志记录到同一个日志文件中,可以在每个Python文件中使用同一个日志文件名和模式:
```python
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
```
5. 如果需要将日志记录到不同的日志文件中,可以为每个Python文件设置不同的日志文件名:
```python
logging.basicConfig(filename='example1.log', filemode='w', level=logging.DEBUG)
logging.basicConfig(filename='example2.log', filemode='w', level=logging.DEBUG)
```
通过以上步骤,你可以在多个Python文件中使用logging模块记录日志,并且将日志记录到同一个或不同的日志文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)