3

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?

ajreal
  • 46,720
  • 11
  • 89
  • 119
Bin Chen
  • 61,507
  • 53
  • 142
  • 183

2 Answers2

5

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
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • 2
    There's also logging.exception(msg) that looks at the exception context and automagically adds a traceback. – Tobu Nov 14 '10 at 03:29
2

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

knitti
  • 6,817
  • 31
  • 42