pythonpython-3.xloggingbloggerpython-logging

What could be the root cause of "TypeError: RootLogger object is not callable" in Python logger module?


I could not find a single solution on this topic except for a random forum post, so posting it here in the hopes that whoever comes across this in the future might also get the information directly. This is what I did:

I wanted to set up logging for some unit test cases. Code went like this:

import unittest
import logging

logging.basicConfig(filename="Testing.log", format="%(asctime)s:%(levelname)s: %(message)s", level=logging.DEBUG, filemode='w+')

def utility_method():
 # do some stuff
 logging.getLogger().debug("This is a debug message")

class TestingStuff(unittest.TestCase):

  loggerInstance = None
  @classmethod
  def setUpClass(cls):
    # do setup stuff
    global logging
    TestingStuff.loggerInstance = logging.getLogger()
 
  @classmethod
  def tearDownClass(cls):
    # do cleanup stuff
    pass

  def test_T_01(self):
    self.loggerInstance("Testing T_01")

  def test_T_02(self):
    self.loggerInstance("Testing T_02")

if __name__=="__main__":
  unittest.main()

This threw the error :

EE
======================================================================
ERROR: test_T_01 (__main__.TestingStuff)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\User\Testing\test.py", line 25, in test_T_01
    self.loggerInstance("Testing T_01")
TypeError: 'RootLogger' object is not callable

======================================================================
ERROR: test_T_02 (__main__.TestingStuff)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\User\Testing\test.py", line 28, in test_T_02
    self.loggerInstance("Testing T_02")
TypeError: 'RootLogger' object is not callable

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (errors=2)

Solution

  • The root cause of this is very simple. This can be caused by a simple syntax error - you need to access the log object through a method corresponding to logging severity (info, debug, etc), and not directly.

    So this was incorrect :

      def test_T_01(self):
        self.loggerInstance("Testing T_01")
    
      def test_T_02(self):
        self.loggerInstance("Testing T_02")
    

    It should have been instead:

      def test_T_01(self):
        self.loggerInstance.info("Testing T_01") # notice printing through info() and not directly
    
      def test_T_02(self):
        self.loggerInstance.info("Testing T_02")