1

Is it possible to dump all errors reported by the Python Interpreter into a log stored as say /var/log/python.log regardless of what script/command caused them? What would be the best way to do this if it's possible?

James
  • 3,957
  • 4
  • 37
  • 82
  • 2
    This should help: [Calling a hook function every time an Exception is raised](http://stackoverflow.com/questions/1029318/calling-a-hook-function-every-time-an-exception-is-raised) – mata Jul 04 '13 at 19:39

2 Answers2

2

Ok, admittedly redirecting stderr may not be the best answer. So another solution would be using sys.excepthook.

Below is an example of it being used.

import sys
import logging
import traceback

LOGFILE = '/var/log/python.log'

def log_uncaught_exceptions(ex_cls, ex, tb):
    logging.critical(''.join(traceback.format_tb(tb)))
    logging.critical('{0}: {1}'.format(ex_cls, ex))

def main():
    raise Exception


if __name__ == '__main__':
    logging.basicConfig(
        level=logging.DEBUG,
        filename=LOGFILE,
        filemode='w')

    sys.excepthook = log_uncaught_exceptions

    main()

Unlike redirecting stderr it will only log the errors from the interpreter and not anything else the script outputs to std*.

Look at this link for more details.

luke
  • 1,005
  • 7
  • 19
  • You should have edited your answer with the further info rather than posting a new one. – hd1 Jul 04 '13 at 21:02
  • Sorry, I thought as they were two different solutions they should be two different answers. – luke Jul 04 '13 at 21:04
  • No worries, I tend to stick to the one answer per user mantra, but your mileage may vary. – hd1 Jul 04 '13 at 21:05
1

Just redirect stderr.

python script.py 2> /var/log/python.log

luke
  • 1,005
  • 7
  • 19
  • 1
    That would also redirect anything the script outputs to stderr, so it's not really an answer to the question. – rodion Jul 04 '13 at 20:06