2

I'm declaring and setting the log level on a logger object like this:

logger = logging.getLogger(__name__)
loglevel = 'DEBUG' # actually taken from a config in my code
logger.setLevel(logging.getLevelName(loglevel))

How can I set the log format in this case? I tried logger.setFormat and logger.setFormatter, they throw attribute errors.

Every guide I read talks about logging.basicConfig(format=FORMAT), but I'm using a logger and not calling directly logging.

1 Answer 1

5

There is an example in the docs, here. Create a handler, set the formatter, then add the handler to the logger:

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setFormatter(logging.Formatter('%(name)-12s: %(message)s'))
logger.addHandler(console)
logger.debug('Hi')

prints

__main__    : Hi
Sign up to request clarification or add additional context in comments.

Comments

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.