3

Suppose I catch an exception, and I want to log it. How do I do that? Where do I specify where to log that to?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

4
virhilo tmp $ cat l.py 
import logging

logging.basicConfig(filename='exceptions.log', level=logging.DEBUG)

try:
    1/0
except ZeroDivisionError as e:
    logging.debug(e)
virhilo tmp $ python2 l.py 
virhilo tmp $ cat exceptions.log 
DEBUG:root:integer division or modulo by zero
virhilo tmp $ 

instead od e you can use traceback.print_exc() to get more detailed report

virhilo
  • 6,568
  • 2
  • 29
  • 26
0

You can use the traceback class.

Like this: traceback.print_exc(file=open("errlog.txt","a"))

Here is an example (from here):

#!/usr/bin/env python
import sys, traceback

def main():
    l=[1,2,3,4]
    print l[4]

if __name__=="__main__":
    try:
        main()
    except:
        print "Trigger Exception, traceback info forward to log file."
        traceback.print_exc(file=open("errlog.txt","a"))
        sys.exit(1)

Or, if you want to log exceptions in Django, check out this thread.

How do you log server errors on django sites

Community
  • 1
  • 1
Arseny
  • 5,159
  • 4
  • 21
  • 24