ActiveState Code

Recipe 576819: Logging to console .. without surprises


logging.StreamHandler is not the best way to log to console .. as it prints everything to sys.stderr by default. You can configure it to log to sys.stdout .. but that means even error/exception will be printed to sys.stdout.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class ConsoleHandler(logging.StreamHandler):
    """A handler that logs to console in the sensible way.

    StreamHandler can log to *one of* sys.stdout or sys.stderr.

    It is more sensible to log to sys.stdout by default with only error
    (logging.ERROR and above) messages going to sys.stderr. This is how
    ConsoleHandler behaves.
    """

    def __init__(self):
        logging.StreamHandler.__init__(self)
        self.stream = None # reset it; we are not going to use it anyway

    def emit(self, record):
        if record.levelno >= logging.ERROR:
            self.__emit(record, sys.stderr)
        else:
            self.__emit(record, sys.stdout)

    def __emit(self, record, strm):
        self.stream = strm
        logging.StreamHandler.emit(self, record)

    def flush(self):
        # Workaround a bug in logging module
        # See:
        #   http://bugs.python.org/issue6333
        if self.stream and hasattr(self.stream, 'flush') and not self.stream.closed:
            logging.StreamHandler.flush(self)

Comments

  1. 1. At 4:27 p.m. on 8 jul 2009, Sridhar Ratnakumar (the author) said:

    An expanded version of this recipe, with support verbosity level and smart logging levels, is available here: http://code.activestate.com/recipes/576836/

Sign in to comment