Skip to content

Commit db07164

Browse files
committed
Added a logging cookbook entry on customized exception formatting.
1 parent ff018e4 commit db07164

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

‎Doc/howto/logging-cookbook.rst‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2033,3 +2033,58 @@ A couple of extra points to note:
20332033
information on how logging supports using user-defined objects in its
20342034
configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
20352035

2036+
2037+
.. _custom-format-exception:
2038+
2039+
Customized exception formatting
2040+
-------------------------------
2041+
2042+
There might be times when you want to do customized exception formatting - for
2043+
argument's sake, let's say you want exactly one line per logged event, even
2044+
when exception information is present. You can do this with a custom formatter
2045+
class, as shown in the following example::
2046+
2047+
import logging
2048+
2049+
class OneLineExceptionFormatter(logging.Formatter):
2050+
def formatException(self, exc_info):
2051+
"""
2052+
Format an exception so that it prints on a single line.
2053+
"""
2054+
result = super(OneLineExceptionFormatter, self).formatException(exc_info)
2055+
return repr(result) # or format into one line however you want to
2056+
2057+
def format(self, record):
2058+
s = super(OneLineExceptionFormatter, self).format(record)
2059+
if record.exc_text:
2060+
s = s.replace('\n', '') + '|'
2061+
return s
2062+
2063+
def configure_logging():
2064+
fh = logging.FileHandler('output.txt', 'w')
2065+
f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
2066+
'%d/%m/%Y %H:%M:%S')
2067+
fh.setFormatter(f)
2068+
root = logging.getLogger()
2069+
root.setLevel(logging.DEBUG)
2070+
root.addHandler(fh)
2071+
2072+
def main():
2073+
configure_logging()
2074+
logging.info('Sample message')
2075+
try:
2076+
x = 1 / 0
2077+
except ZeroDivisionError as e:
2078+
logging.exception('ZeroDivisionError: %s', e)
2079+
2080+
if __name__ == '__main__':
2081+
main()
2082+
2083+
When run, this produces a file with exactly two lines::
2084+
2085+
28/01/2015 07:21:23|INFO|Sample message|
2086+
28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n File "logtest7.py", line 30, in main\n x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|
2087+
2088+
While the above treatment is simplistic, it points the way to how exception
2089+
information can be formatted to your liking. The :mod:`traceback` module may be
2090+
helpful for more specialized needs.

0 commit comments

Comments
 (0)