I have following code in my colab notebook:
# Cell 1
import logging
# Cell 2
class MyClass:
def __init__(self):
self.configureLogger()
self.fileLogger.info('info log to file')
self.consoleLogger.debug('debug log to console')
def configureLogger(self):
# https://stackoverflow.com/a/56144390/6357916
# logging.basicConfig(level=logging.NOTSET)
self.fileLogger = logging.getLogger('fileLogger2')
if not self.fileLogger.hasHandlers():
self.fileLogger.setLevel(logging.INFO)
formatter1 = logging.Formatter("%(asctime)s,%(message)s")
file_handler = logging.FileHandler('log.txt')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter1)
self.fileLogger.addHandler(file_handler)
self.consoleLogger = logging.getLogger('consoleLogger2')
if not self.consoleLogger.hasHandlers():
self.consoleLogger.setLevel(logging.DEBUG)
formatter2 = logging.Formatter("%(message)s")
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter2)
self.consoleLogger.addHandler(console_handler)
c = MyClass()
There MyClass
has a method called configureLogger()
which configures two loggers:
fileLogger
: logs to fileconsoleLogger
: logs t console
MyClass.__init__()
call this method and uses both of these loggers to log single message each. But nothing gets logged to console. Nor does log.txt
file gets created.
I am expecting it to log debug log to console
to console and info log to file
to file. This is how it is behaving on my local machine, but fails on colab
What I am missing here?
Update
After commenting both line containing if ...
, it is now printing
2023-04-07 20:10:20,860,info log to file
to file and
INFO:fileLogger2:info log to file
debug log to console
DEBUG:consoleLogger2:debug log to console
to console.
It means those if
conditions are false
causing no file handler are getting added and that is why nothing was getting logged. But those if conditions should be true
initially right (as logger should not have any handler to start with)?