Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify output format of Python logger

Tags:

python

logging

I'm trying to modify 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. First one doesn't change the format. Second one throws an index error when I try to access logger.handlers[0].

I don't want to write my own handler, just modify the format on the default handler. Is there an easy way?

like image 658
Yarin Avatar asked Aug 05 '12 20:08

Yarin


1 Answers

First one changes format of

logging.<severity>("message")

In other words, when you set format in the first sample, you don't need to acquire separate logger instance, you can just use logging itself. That being said it can have unwanted effects if any other modules you're using also use logging.

If you want to change format of your separate logger 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)
like image 148
favoretti Avatar answered Sep 19 '22 15:09

favoretti