I have setup logging as follows:
def setUp():
LOG_FORMAT = '%(asctime)s %(levelname)-8s %(name)s %(message)s'
#LOG_FORMAT = '%(asctime)s %(name)s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
formatter = logging.Formatter(LOG_FORMAT)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
logging.getLogger().addHandler(ch)
LOG_FILENAME = 'file.log'
fh = logging.FileHandler(LOG_FILENAME, 'w')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logging.getLogger().addHandler(fh)
However, the console still shows DEBUG messages. Am I missing something here?
Note that setting the level to ERROR on fh works fine.
I think you need to remove the call to
logging.basicConfig. That function adds anotherlogging.StreamHandlerthat probably is the one that is printing the messages you don’t want to be printed.To check this you can take a look at the
handlersattribute for the root logger (it’s a list with all the handlers being used) and verify how manylogging.StreamHandlersthere are. Also, probably the message with level set tologging.ERRORare printed twice because of the twologging.StreamHandlers.My final advice is avoid using
logging.basicConfigif you’re going to explicitly configure the handlers in the code.Edit: Just for completeness, the source code of
logging.BasicConfigis as follows:where you can see that unless
filenameis passed, alogging.StreamHandleris created.