Snort5121
Snort5121

Reputation: 171

Python Logger object is not callable

I'm trying to write a module to use it in different scripts

import logging
from logging.handlers import RotatingFileHandler


_logger_name = "Nagios"
_print_format = "%(asctime)s - %(levelname)s - %(message)s"
_level = logging.DEBUG

class Log():


    def __init__(self,log_file,logger_name=_logger_name,level=_level):
        self.log_file = log_file
        self.logger_name = logger_name
        self.level = level

    def getLog(self):

        """
        Return the logging object

        """
       _logger = logging.getLogger(self.logger_name)
       _logger.setLevel(self.level)
       _logger.addHandler(self._rotateLog())

       return _logger

    def _rotateLog(self):

       """
       Rotating the log files if it exceed the size
       """
       rh = RotatingFileHandler(self.log_file,
                             maxBytes=20*1024*1024, backupCount=2)
       formatter = logging.Formatter(_print_format)
       rh.setFormatter(formatter)
       return rh

log = Log("kdfnknf").getLog()
log("hello")

I see the following error:

Traceback (most recent call last):
File "nagiosLog.py", line 45, in <module>
  log("hello")
TypeError: 'Logger' object is not callable

Any idea why I'm getting this error,

When debugged using pdb I do see it returns the object and printing the dir(log) I don't see the Logger module in it.

Am I missing something here

Upvotes: 9

Views: 11708

Answers (3)

user22605465
user22605465

Reputation: 1

I had the same problem as OP. Old instructions on implementing custom logging levels will have code that calls the logger constructor, instead of the log method. The newer-than-that-but-not-all-that-new functionality is to use self._log.log(level, et al...

Edit to add: so, instead of log("hello") you'd need to call log.log(logging.INFO, "hello") or write a wrapper for that function in the Log class that hardcoded the level you want everything logged at and takes only the the message.

Upvotes: 0

Prateek Sen
Prateek Sen

Reputation: 422

log("Hello")

This is wrong. Correct is

log.info("Hello")

log must be printed with logging level i.e. info/error/warning

Upvotes: 10

TemporalWolf
TemporalWolf

Reputation: 7952

See the logging docs:

You have to use a function, you can't just call Logger:

Logger.info(msg, *args, **kwargs)

Logs a message with level INFO on this logger. The arguments are interpreted as for debug().

or

Logger.warning(msg, *args, **kwargs)

Logs a message with level WARNING on this logger. The arguments are >interpreted as for debug().

so instead, do:

log.info("Test info level logging...")

Upvotes: 3

Related Questions