[Django]-In Python, what's the best way to log exceptions to a file?

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

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

👤Arseny

Leave a comment