Change Python logger output format

I am trying to change the output of my Python logger to show the process id.

Two ways I've tried:

import logging FORMAT = "%(asctime)s %(process)s %(thread)s: %(message)s" logging.basicConfig(format=FORMAT) logger = logging.getLogger('my_logger') 

and

 import logging FORMAT = "%(asctime)s %(process)s %(thread)s: %(message)s" logger = logging.getLogger('my_logger') handler = logger.handlers[0] handler.setFormatter(logging.Formatter(FORMAT)) 

Nada. The first does not change the format. The second causes an index error when trying to access logger.handlers[0] .

I do not want to write my own handler, just change the format for the default handler. Is there an easy way?

+4
source share
1 answer

Format changes first

 logging.<severity>("message") 

In other words, when you set the format in the first example, you do not need to purchase a separate instance of the log, you can just use logging . However, it may have undesirable effects if any other modules you use also use logging .

If you want to change the format of your individual registrar, you can use the following example:

 from logging import StreamHandler, Formatter FORMAT = '%(asctime)-15s %(levelname)-6s %(message)s' DATE_FORMAT = '%b %d %H:%M:%S' formatter = Formatter(fmt=FORMAT, datefmt=DATE_FORMAT) handler = StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger(__name__) logger.addHandler(handler) 
+4
source

All Articles