You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit db07164
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: Doc/howto/logging-cookbook.rst
+55Lines changed: 55 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2033,3 +2033,58 @@ A couple of extra points to note:
2033
2033
information on how logging supports using user-defined objects in its
2034
2034
configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
2035
2035
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
0 commit comments