python traceback single line logging module

Solutions on MaxInterview for python traceback single line logging module by the best coders in the world

showing results for - "python traceback single line logging module"
Serena
07 Aug 2018
1import logging
2
3class OneLineExceptionFormatter(logging.Formatter):
4    def formatException(self, exc_info):
5        """
6        Format an exception so that it prints on a single line.
7        """
8        result = super().formatException(exc_info)
9        return repr(result)  # or format into one line however you want to
10
11    def format(self, record):
12        s = super().format(record)
13        if record.exc_text:
14            s = s.replace('\n', '') + '|'
15        return s
16
17def configure_logging():
18    fh = logging.FileHandler('output.txt', 'w')
19    f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
20                                  '%d/%m/%Y %H:%M:%S')
21    fh.setFormatter(f)
22    root = logging.getLogger()
23    root.setLevel(logging.DEBUG)
24    root.addHandler(fh)
25
26def main():
27    configure_logging()
28    logging.info('Sample message')
29    try:
30        x = 1 / 0
31    except ZeroDivisionError as e:
32        logging.exception('ZeroDivisionError: %s', e)
33
34if __name__ == '__main__':
35    main()
36
37# Output 
3828/01/2015 07:21:23|INFO|Sample message|
3928/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'|
40
41
similar questions