logging 怎么在报出实例化文件的名字
时间: 2023-11-28 13:49:11 浏览: 35
你可以在代码中使用Python内置的logging模块来记录日志,并通过设置Logger的名称来记录实例化文件的名字。具体实现可以参考下面的代码示例:
```python
import logging
logger = logging.getLogger(__name__)
class MyClass:
def __init__(self):
logger.info("Creating instance of MyClass")
```
在上述代码中,我们使用`__name__`作为Logger的名称,这样可以确保每个Logger都与其所在的模块相关联。然后在`__init__`方法中,我们使用`logger.info`方法记录一条日志,其中包含了实例化文件的名字。这样,在运行程序时,你会看到类似以下的日志输出:
```
INFO:my_module.MyClass:Creating instance of MyClass
```
其中,`my_module`是MyClass所在的模块名称,`MyClass`是类名,说明我们成功地记录了实例化文件的名字。
相关问题
怎么让 logging 模块 显示 调用的文件名字和行号
可以通过在 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.logging怎么用handdler设置文件路径
在 Python 的 logging 模块中,可以使用 `FileHandler` 类来将日志记录到指定的文件中。具体来说,可以通过 `filename` 参数来指定日志文件的路径,例如:
```python
import logging
logger = logging.getLogger('example')
logger.setLevel(logging.INFO)
# 创建一个 FileHandler,并将日志记录到 example.log 文件中
handler = logging.FileHandler('example.log')
handler.setLevel(logging.INFO)
# 定义日志输出格式
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
# 将 FileHandler 添加到 logger 中
logger.addHandler(handler)
# 输出日志信息
logger.info('This is an example message.')
```
在上面的示例中,我们首先创建了一个名为 `'example'` 的 logger,并将其日志级别设置为 `logging.INFO`。然后,我们创建了一个 `FileHandler` 对象,并将其日志级别设置为 `logging.INFO`,并将日志文件路径设置为 `'example.log'`。接下来,我们定义了日志输出的格式,并将其应用到 `FileHandler` 对象中。最后,我们将 `FileHandler` 对象添加到 logger 中,并使用 `logger.info()` 方法记录日志信息。
需要注意的是,如果需要在程序中使用多个 logger,可以创建多个 `FileHandler` 对象,并将其分别添加到不同的 logger 中。另外,如果需要在同一个程序中同时将日志记录到控制台和文件中,可以使用 `StreamHandler` 类来将日志记录到控制台中。
相关推荐
![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)