0

I am using the basic python logger in django and it seems to be workng well. I have the logging setup in my setting.py as;

logging.baseConfig(level = logging.NOTSET,    
                   format='a format',    
                   datemt=' a datefmt',    
                   filename='path to log',    
                   filemode = 'a')    
logging.getLogger('').setLevel(logging.NOTSET)    

My question is with regard to propagating exceptions. In my code if I have a try/except clause and catch the exception so I can log it, what is the best way to then propagate that error so that I can redirect to my 500 page. I have been using

try:
    do stuff
except Exception, e:
    logging.error(e)
    raise

but I find that this causes the exeption to be logged twice. Is there another way to do this or am I doing something wrong?

Regards
Andrew

0

2 Answers 2

1

There's no need to catch the exception just so you can log it. You can log it and handle it, or else let it bubble up to some higher level which will log it and handle it. If you want to log exceptions which occur in some view, which you don't want to handle, then you can install some exception middleware which logs the exception and either returns a custom response which you determine, or None (to return whatever response Django would normally return).

There's an example of extensible exception middleware here, which doesn't actually use logging but whose log_exception() method you could subclass to log the exception, or just use that snippet as a guide to provide your own exception middleware - it's basically just a class with a method called process_exception:

class MyExceptionMiddleware:

    def process_exception(self, request, exception):
        #Do your logging here

Also, note that loggers have an exception() method which works like error() but includes traceback information in the log.

Sign up to request clarification or add additional context in comments.

Comments

0

There's a recipe: http://code.activestate.com/recipes/466332/

In any somewhat complex application, you likely want to log and handle most exceptions. The recipe shows a way to separate logging from handling, so that it is not necessary to explicitly invoke the logging mechanism in each try-except clause.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.