Skip to content

Handler for Global Logger in Python

October 11th, 2017 - SoftwareTutorial

While writing a command line tool, I’ve stumbled upon a strange situation: Some logs were written to a file while some others were printed to console. Quite annoying, particularly since every module I use has its own logger via logging.getLogger(__name__).

After some investigation I found out you can access the global logger via logging.getLogger() (note the lack of parameters). So, my new setup is:

hdlr = logging.FileHandler('./data/logs/photo-copy.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)

global_logger= logging.getLogger()
global_logger.addHandler(hdlr)
global_logger.setLevel(logging.WARNING)

Simple.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: