I don't understand how python logging module reads its execution code

Viewed 38

This below is my code


logging.basicConfig(filename='logging2 text', level=logging.INFO,
                    format='%(levelname)s:%(message)s')

class Employee:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    @property
    def fullname(self):
        return('{} {}'.format(self.firstname, self.lastname))

    @property
    def email(self):
        return('{}@gmail.com'.format(self.fullname))

        logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, self.email))

emp1 = Employee('Joe', 'Mama')

When I run the program, it creates the file 'logging2 test' but it records no logs, only a blank file although i've already tell the program to record the logs on line 19, logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, self.email)) really could use some explanation. Thanks

1 Answers

There are two issues. You log after return and hence the log line is never reached.

But your code also contains an infinite recursion. This happens because it calls self.email inside of the email property in the logging line.

To break out of this, you need to know what the email address is at the time of the log.

@property
def email(self):
    email = '{}@gmail.com'.format(self.fullname)
    logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, email))
    return(email)

This sets email to a variable inside the of the function and uses that in both the log and the return statements.

Then when you access the email property, the log line will show as expected.

print(empl.email)

Logs the following:

INFO:Employee info:
Fullname: Joe Mama
Email: Joe Mama@gmail.com
Related