Is this PEP viable?

Peter Otten __peter__ at web.de
Mon Jul 17 12:24:03 EDT 2017


Evan Adler wrote:

> I would like to submit the following proposal. In the logging module, I
> would like handlers (like file handlers and stream handlers) to have a
> field for exc_info printing. This way, a call to logger.exception() will
> write the stack trace to the handlers with this flag set, and only print
> the message and other info to handlers without the flag set. This allows a
> single logger to write to a less detailed console output, a less detailed
> run log, and a more detailed error log.

If I understand you correctly this would go into the Formatter rather than 
the Handler. E. g.:

$ cat log_exception_format.py
import logging
import sys

class MyFormatter(logging.Formatter):
    def __init__(self, fmt=None, datefmt=None, style='%', verbose=0):
        super().__init__(fmt, datefmt, style)
        self.verbose = verbose

    def formatException(self, ei):
        if self.verbose < 1:
            return ""
        elif self.verbose < 2:
            return "{0[0].__name__}: {0[1]}".format(ei)
        else:
            return super().formatException(ei)


formatter = MyFormatter(logging.BASIC_FORMAT, verbose=sys.argv.count("-v"))
handler = logging.StreamHandler()
handler.setFormatter(formatter)

g = logging.getLogger()
g.addHandler(handler)

def f(n):
    if n > 0:
        return f(n-1)
    else:
        1/0
try:
    f(3)
except:
    g.exception("foo")
$ python3 log_exception_format.py
ERROR:root:foo
$ python3 log_exception_format.py -v
ERROR:root:foo
ZeroDivisionError: division by zero
$ python3 log_exception_format.py -v -v
ERROR:root:foo
Traceback (most recent call last):
  File "log_exception_format.py", line 31, in <module>
    f(3)
  File "log_exception_format.py", line 27, in f
    return f(n-1)
  File "log_exception_format.py", line 27, in f
    return f(n-1)
  File "log_exception_format.py", line 27, in f
    return f(n-1)
  File "log_exception_format.py", line 29, in f
    1/0
ZeroDivisionError: division by zero
$ 

(Note that this is just a sketch; for the above to work reliably the 
format() method has to be changed to avoid caching the result of the 
formatException() call)





More information about the Python-list mailing list