0

I am writing a custom logging module which can be imported into all my codes to create standard logs. Here is my logging module log_info.py:

class CustomLogger:
    def custom_logger(self, loglevel= logging.INFO):
        logger_name= inspect.stack()[1][3]
        logger= logging.getLogger(logger_name)
        logger.setLevel(loglevel)
        log_message_format= logging.Formatter('%(levelname)s:%(name)s,:%(message)s')
        file_handler= logging.FileHandler('sla_data.log')
        file_handler.setFormatter(log_message_format)
        logger.addHandler(file_handler)
        return logger

And here is my code where I am importing the above module:

from log_info import CustomLogger
#code to do a bunch of things
...
#calls the custom logging module as
logs= CustomLogger.custom_logger(loglevel= logging.INFO)
logs.info(f'logs: started_by: {windows_user}, started_at: {etl_start},\
     ended_at: {etl_end}, with no errors')

But I get this error: TypeError: custom_logger() missing 1 required positional argument: 'self'.

Update: I removed 'self' from custom_logger() and it worked. I probably don't understand the usage of 'self' too well. I'd like to understand more and also how can this code be improved?

1
  • 1
    This resulted from calling the method on the class rather than on the object itself. If you want to Generally you'd create an instance of the class, then self would be passed in automatically. But there are many different ways to use objects in python; everything is an object. I would start here: docs.python.org/3/tutorial/classes.html. Commented Mar 4, 2022 at 7:56

1 Answer 1

1

You are calling object method via class reference right here

logs = CustomLogger.custom_logger(loglevel = logging.INFO)

Instead you either should use object reference, e.g.

logs = CustomLogger().custom_logger(loglevel = logging.INFO)

or you can make custom_logger a static method as there is no object/class reference

class CustomLogger:
    @staticmethod
    def custom_logger(loglevel = logging.INFO):
        ...

P.S

Take a minute formatting your spaces to satisfy PEP8 conventions

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.