Juicy
Juicy

Reputation: 12500

Set log format on logger (without basicConfig)

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.

Upvotes: 2

Views: 1187

Answers (1)

unutbu
unutbu

Reputation: 879073

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

Upvotes: 5

Related Questions