dcsan
dcsan

Reputation: 12275

how to get consistent python logging format?

I'm trying to set the python logging format, but it seems to ignore my config settings. Is there something to do with hierarchy of loggers that I don't understand?

I have something like

import logging
logging.basicConfig(format='%(message)s')

but all the logs still come out with timecode etc.

I read somewhere about how logging format is inherited.

I've tried adding this to many different files in case somehow the first encounter with a logging config sets it for the whole session.

The only way I can get this to stick is creating a custom logger in every file, which is tedious with like:

logger = logging.getLogger('name')
# then configure and use logger.info() etc.

Trivial thing, but this has bugged me for a long time! Working on cluttered remote shells where I want to get rid of all the time code guff.

Upvotes: 1

Views: 1247

Answers (1)

wim
wim

Reputation: 362756

You are correct that the first logging configuration call sets it for the whole session. That is actually the expected behavior. See the docs:

The call to basicConfig() should come before any calls to debug(), info() etc. As it’s intended as a one-off simple configuration facility, only the first call will actually do anything: subsequent calls are effectively no-ops.

Therefore, you should find the first configuration and set your log format there, removing all subsequent configurations.

However, if that is not practicable then there is a workaround available since Python 3.8 to force reconfiguring the logging system:

logging.basicConfig(format='%(message)s', level=logging.INFO, force=True)

Demo:

import logging 

log = logging.getLogger(__name__)

logging.basicConfig(format='%(levelname)s %(message)s', level=logging.INFO)
log.info("first")
logging.basicConfig(format='%(message)s', level=logging.INFO, force=True)
log.info("second")

Outputs:

INFO first
second

Upvotes: 1

Related Questions