Skip to main content
 首页 » 编程设计

Python 日志记录 : how to save class attributes values in the log file

2025年05月04日16freeliver54

我是 Python 新手,除了日志文件中长管道的结果外,我还想保存在管道中创建的一些实例的参数/类属性。

理想情况下,这不应过多污染实现该类的代码。

如果解决方案只考虑类的实例并将其属性写入日志文件,而不触及所有类的实现,那就更好了。

有什么建议,或者上帝的实践建议?

--- 编辑:

一个未打磨和简化的版本初始尝试(如评论中所问)是我能想到的最明显的尝试,包括添加一个方法,该方法在调用该方法时返回的字符串中查询类的属性:

在一个包含2个模块main.py和a_class.py的python包中写成如下:

>> cat main.py 
 
import logging 
from a_class import MyClass 
 
 
logging.basicConfig(filename='example.log',level=logging.DEBUG) 
 
logging.warning('Print this to the console and save it to the log') 
logging.info('Print this to the console') 
 
o = MyClass() 
o.attribute_1 = 1 
o.attribute_2 = 3 
o.attribute_3 = 'Spam' 
 
logging.info(o.print_attributes()) 

和

>> cat a_class.py 
 
class MyClass(): 
    def __init__(self): 
        self.attribute_1 = 0 
        self.attribute_2 = 0 
        self.attribute_3 = 0 
 
    def print_attributes(self): 
        msg = '\nclass.attribute_1 {}\n'.format(self.attribute_1) 
        msg += 'class.attribute_2 {}\n'.format(self.attribute_2) 
        msg += 'class.attribute_3 {}\n'.format(self.attribute_3) 
        return msg 

example.log 包含我想要的内容,即:

WARNING:root:Print this to the console and save it to the log 
INFO:root:Print this to the console 
INFO:root: 
class.attribute_1 1 
class.attribute_2 3 
class.attribute_3 Spam 

在重新表述问题时,是否有一种方法可以对类的属性执行相同的查询并将其发送到日志,而无需在类本身中添加任何类型的 print_attributes 方法?

请您参考如下方法:

使用内置的__dict__

class MyClass(): 
    def __init__(self): 
        self.attribute_1 = 0 
        self.attribute_2 = 0 
        self.attribute_3 = 0 
 
o = MyClass() 
print o.__dict__ 

输出:

{'attribute_2': 0, 'attribute_3': 0, 'attribute_1': 0} 

根据需要在日志记录中使用它。