5

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?

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What do you have to import to get Formatter working? I have from formatter import Formatter and get NameError: name 'Formatter' is not defined
Success! The StreamHandler recipe worked for me- thanks favoretti

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.