How to redirect python runtime errors?

I write a daemon server using python, sometimes python runtime errors occur, for example, an incorrect variable type. This error will not cause the process to exit.

Is it possible to redirect such a runtime error to a log file?

+3
source share
2 answers

You seem to be asking two questions.

So that your process does not depend on errors, you need to catch all exceptionthat were raised with try...except...finally.

You also want to redirect all output to the log. Fortunately, Python provides a comprehensive loggingmodule for your convenience.

Example, for your pleasure and admiration:

#!/usr/bin/env python

import logging
logging.basicConfig(filename='warning.log', level=logging.WARNING)

try:
    1/0
except ZeroDivisionError, e:
    logging.warning('The following error occurred, yet I shall carry on regardless: %s', e)

This kindly emits:

% cat warning.log
WARNING:root:The following error occurred, yet I shall carry on regardless: integer division or modulo by zero
+5

traceback. RuntimeError, ( logging).

+2

Source: https://habr.com/ru/post/1774742/