I am using the logging
module in Python to write debug and error messages.
I want to write to file all messages of logging.DEBUG
or greater.
However, I only want to print to the screen messages of logging.WARNING
or greater.
Is this possible using just one Logger
and one FileHandler
?
No. File and Screen output means you need two handlers.
As it has been mentioned, handlers are so easy to create and add that you're probably better off just using two handlers. If, however, for some reason you want to stick to one, the Python logging cookbook has a section describing more or less what you want to do: logging to both console and file, but at different levels (it even shows you how to do different formatting). It does it with a single
StreamHandler
rather than aFileHandler
, though:Edit: As discussed in the comments this code still generates two handlers, but "hides" one construction through the use of basicConfig(). I would strongly encourage you to create both explicitly.
You can use the same handler. This example log messages to file with log.debug() and log.info() to console: