I'm new to logging in python and I would like to save, other than the outcome of a long pipeline in the log file, also the parameters/class attributes of some of the instance created in the pipeline.
Ideally this should not pollute too much the code where the class is implemented.
Even better if the solution takes into account only the instance of the class and writes its attribute in the log file without touching at all the class implementation.
Any suggestion, or god practice advice?
--- Edit:
An unpolished and simplified version initial attempt (as asked in the comment) is the most obvious I could think of, and consist in adding a method that queries the attribute of the class in a string to be returned when the method is called:
In a python package with 2 modules main.py
and a_class.py
written as follows:
>> 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())
and
>> 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
The example.log contains what I wanted, which is:
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
In reformulating the question, is there a way of doing the same query to the attribute of the class and send it to the log without adding any kind of print_attributes
method in the class itself?