nowox
nowox

Reputation: 29178

How to add a logger to a module in Python?

I am discovering logging and I would like to integrate it inside a class for external usage. It means, the user can either choose to ignore the logging feature or bind an handler to it.

I currently have this in my test module:

import logging
class Test:
   def __init__(self):
      self.logger = logging.getlogger(__module__ + '.Test')

   def hello(self):
      self.logger.warn('Hello World!')


test = Test()
test.hello()

With this I get the error

No handlers could be found for logger

I precisely don't want to bind a handler to this logger otherwise I may override the choice of the parent. I thought the default handler was Nullhandler.

What would be the correct pattern to integrate a logging feature inside an independant module?

Of course one solution would be to check if no handlers are binded to it:

if not len(self.logger): l.addHandler(logging.NullHandler())

Upvotes: 0

Views: 677

Answers (1)

RobertB
RobertB

Reputation: 1929

This is what I use in one of my projects.

def get_logger(log_level,log_name='YourNameGoesHere'):
    logger = logging.getLogger(log_name)
    if not logger.handlers:
        logger.setLevel(log_level)
        ch = logging.StreamHandler()
        ch.setLevel(log_level)
        ch.setFormatter(logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        ))
        logger.addHandler(ch)
        logger.propagate = 0
    return logger

Upvotes: 1

Related Questions