Pedro Gabriel Lima
Pedro Gabriel Lima

Reputation: 1172

How self works inside a class in python

I need some help with the following code:

import logging

class TestLoggin:

    def __init__(self):
        # Create the Logger
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)

        # Create the Handler for logging data to a file
        logger_handler = logging.FileHandler('output.log')
        logger_handler.setLevel(logging.DEBUG)

        # Create a Formatter for formatting the log messages
        logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',  datefmt='%d-%m-%Y %H:%M:%S')

        # Add the Formatter to the Handler
        logger_handler.setFormatter(logger_formatter)

        # Add the Handler to the Logger
        self.logger.addHandler(logger_handler)

The logging module works fine when the setup is inside the __init__ method. But if I try to remove it to a new method, as below:

import logging

class TestLoggin:

    def __init__(self):
        self.logger = self.setup_logger(output_path)

    def example_using_logger(self):
        self.logger.error('it will raise an error')    

    def setup_logger(self, output_path):
        # Create the Logger
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # Create the Handler for logging data to a file
        logger_handler = logging.FileHandler(output_path)
        logger_handler.setLevel(logging.DEBUG)

        # Create a Formatter for formatting the log messages
        logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',  datefmt='%d-%m-%Y %H:%M:%S')

        # Add the Formatter to the Handler
        logger_handler.setFormatter(logger_formatter)

        # Add the Handler to the Logger
        return logger.addHandler(logger_handler)

And try to use the logger module self.logger.error('it will raise an error'), I got the following error: AttributeError: 'NoneType' object has no attribute 'error'.

I know the raised error is because logger is not recognized as part of the module, but as just a new variable. That is because I didn't grasp the fundamental of self. I'm new to Python, so I need some help here: How can I fix this, and the why of the problem. This last one would help me to understand a little more about the self.

Thanks in advance!

Upvotes: 1

Views: 92

Answers (1)

Elizabeth
Elizabeth

Reputation: 91

The issue is that logger.addHandler() isn't returning anything, so you're assigning None (returned from logger.addHandler()) to self.logger.

Try this:

# Add the Handler to the Logger
logger.addHandler(logger_handler)
return logger

Upvotes: 3

Related Questions