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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With