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 possi开发者_开发技巧ble for me to redirect such runtime error to a log file?
It looks like you are asking two questions.
To prevent your process from exiting on errors, you need to catch all exception
s 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
Look at the traceback
module. If you catch a RuntimeError
, you can write it to the log (look at the logging
module for that).
精彩评论