user2242044
user2242044

Reputation: 9213

Python Logging levels don't seem to be working

I would like to log info level information to a file and debug level info to the console. I am using StreamHandlers, but both logging.info and logging.debug both log to the console and file. I would like the console to just show test1 and the file to just show test.

import logging
import os

rootLogger_file = logging.getLogger()
rootLogger_file.setLevel(logging.INFO)

rootLogger_console = logging.getLogger()
rootLogger_console.setLevel(logging.DEBUG)

fileHandler = logging.FileHandler('info', "w")

rootLogger_file.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
rootLogger_console.addHandler(consoleHandler)

rootLogger_file.info('test')
rootLogger_console.debug('test1')

Upvotes: 2

Views: 43

Answers (1)

user2390182
user2390182

Reputation: 73470

You are only creating a single logger with level DEBUG and you are adding both handlers to it. From the docs:

Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.

f = logging.getLogger()
f.setLevel(logging.INFO)

c = logging.getLogger()  # returns the same object as before!
c.setLevel(logging.DEBUG)

f is c
# True  # f and c are the same object!

f.level
# 10  # DEBUG
c.level
# 10  # DEBUG

Since the one logger you have has level DEBUG (which means it also logs INFO and all other levels) and is picked up by both handlers, both messages are shown on the console and in the file. You have to give them different names upon creation:

f = logging.getLogger('f')
f.setLevel(logging.INFO)
c = logging.getLogger('c')
c.setLevel(logging.DEBUG)
# ...
f.info('test')  # logs to file
c.debug('test1') # logs to console

Upvotes: 3

Related Questions