Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect python runtime errors?

I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit.

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

like image 664
Bin Chen Avatar asked May 04 '26 05:05

Bin Chen


2 Answers

It looks like you are asking two questions.

To prevent your process from exiting on errors, you need to catch all exceptions that are raised using try...except...finally.

You also wish to redirect all output to a log. Happily, Python provides a comprehensive logging module for your convenience.

An example, for your delight and delectation:

#!/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 graciously emits:

% cat warning.log
WARNING:root:The following error occurred, yet I shall carry on regardless: integer division or modulo by zero
like image 137
Johnsyweb Avatar answered May 05 '26 18:05

Johnsyweb


Look at the traceback module. If you catch a RuntimeError, you can write it to the log (look at the logging module for that).

like image 33
knitti Avatar answered May 05 '26 17:05

knitti