Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging: how to save class attributes values in the log file

Tags:

python

logging

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?

like image 841
SeF Avatar asked Feb 01 '26 05:02

SeF


1 Answers

Use the inbuilt __dict__

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

o = MyClass()
print o.__dict__

Outputs:

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

Use it in logging as you want to.

like image 177
Arunmozhi Avatar answered Feb 02 '26 18:02

Arunmozhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!