Logging module not writing to file Logging module not writing to file powershell powershell

Logging module not writing to file


I add the following lines before the logging.basicConfig() and it worked for me.

for handler in logging.root.handlers[:]:    logging.root.removeHandler(handler)


You can try running this snippet in your main file.

import logging logging.basicConfig(    level=logging.INFO,     format='%(asctime)s [%(levelname)s] - %(message)s',    filename='filename.txt')  # pass explicit filename here logger = logging.get_logger()  # get the root loggerlogger.warning('This should go in the file.')print logger.handlers   # you should have one FileHandler object


If you are using 'root' logger which is by default has name "", than you can do this trick:

logging.getLogger().setLevel(logging.INFO)    logger = logging.getLogger('')logger.handlers = []

In addition you may want to specify logging level as in code above, this level will persist for all descendant loggers.

If instead, you specified particular logger, than do

logger = logging.getLogger('my_service')logger.handlers = []fh = logging.FileHandler(log_path)fh.setLevel(logging.INFO)# create console handlerch = logging.StreamHandler()ch.setLevel(logging.INFO)logger.addHandler(fh)logger.addHandler(ch)logger.info('service started')

The above code will create new logger 'my_service'. In case that logger has been already created it clears all handles. That it adds handles for writing in specified file and console. See official documentation as well.

You can also use hierarchical loggers. It is done directly.

logger = logging.getLogger('my_service.update')logger.info('updated successfully')