I’m logging events in my python code uing the python logging module. I have 2 logging files I wish to log too, one to contain user information and the other a more detailed log file for devs. I’ve set the the two logging files to the levels I want (usr.log = INFO and dev.log = ERROR) but cant work out how to restrict the logging to the usr.log file so only the INFO level logs are written to the log file as opposed to INFO plus everthing else above it e.g. INFO, WARNING, ERROR and CRITICAL.
This is basically my code:-
import logging
logger1 = logging.getLogger('')
logger1.addHandler(logging.FileHandler('/home/tmp/usr.log')
logger1.setLevel(logging.INFO)
logger2 = logging.getLogger('')
logger2.addHandler(logging.FileHandler('/home/tmp/dev.log')
logger2.setLevel(logging.ERROR)
logging.critical('this to be logged in dev.log only')
logging.info('this to be logged to usr.log and dev.log')
logging.warning('this to be logged to dev.log only')
Any help would be great thank you.
I am in general agreement with David, but I think more needs to be said. To paraphrase The Princess Bride – I do not think this code means what you think it means. Your code has:
which means that
logger1andlogger2are the same logger, so when you set the level oflogger2to ERROR you actually end up setting the level oflogger1at the same time. In order to get two different loggers, you would need to supply two different logger names. For example:Worse still, you are calling the logging module’s
critical(),info()andwarning()methods and expecting that both loggers will get the messages. This only works because you used the empty string as the name for bothlogger1andlogger2and thus they are not only the same logger, they are also the root logger. If you use different names for the two loggers as I have suggested, then you’ll need to call thecritical(),info()andwarning()methods on each logger individually (i.e. you’ll need two calls rather than just one).What I think you really want is to have two different handlers on a single logger. For example:
Once you’ve made this change, then you can use filters as David has already mentioned. Here’s a quick sample filter:
You can apply the filter to each of the two handlers like this:
This will restrict each handler to only write out log messages at the level specified.