[英]Python logging: how to save class attributes values in the log file
我是剛接觸python的人,我想保存它,除了日志文件中長管道的結果外,還保存一些在管道中創建的實例的參數/類屬性。
理想情況下,這樣做不應過多污染實現該類的代碼。
如果該解決方案僅考慮該類的實例並將其屬性寫入日志文件,而又不涉及所有的類實現,則更好。
有什么建議,還是上帝的實踐建議?
-編輯:
我可以想到的最簡單,未經拋光的簡化版本嘗試(如評論中所述),包括添加一個方法,該方法在調用該方法時以字符串形式查詢類的屬性:
在具有2個模塊的python軟件包中, main.py
和a_class.py
編寫如下:
>> 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
方法?
我建議為您的類實現__str__
或__repr__
,以便很好地顯示所有顯着的屬性值。
然后,您可以將實例記錄為簡單值: log.info("Now foo is %s", foo_instance).
一個完整的例子:
class Donut(object):
def __init__(self, filling, icing):
self.filling = filling
self.icing = icing
def __repr__(self):
return 'Donut(filling=%r, icing=%r)' % (self.filling, self.icing)
donut = Donut('jelly', 'glaze')
import logging
logging.basicConfig()
logging.getLogger().warn('Carbs overload: one %s too much', donut)
輸出:
2017-10-25 10:59:05,302 9265 WARNING Carbs overload: one Donut(filling='jelly', icing='glaze') too much
使用內置的__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}
根據需要在日志記錄中使用它。
我同意@Iguananaut所說的那樣,沒有神奇的方法。 但是,以下方法可以解決問題。 它比您編寫的IMO的print_attributes
方法更好。
import logging
logging.basicConfig()
logger = logging.getLogger('ddd')
logger.setLevel(logging.DEBUG)
class A(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
return "\n".join(["{} is {}".format(k, v)
for k, v in self.__dict__.iteritems()])
a = A(1, 2, 3)
logger.debug(a)
結果看起來像這樣-
{12:43}~ ➭ python logging_attrib.py
DEBUG:ddd:a is 1
c is 3
b is 2
請讓我知道你的想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.