Reputation: 1314
A common functionality that I would like to write a decorator for is the following:
in a django view, I have following code:
def view(request):
try:
# do stuff and return success case view response
return render_to_response(...)
except:
# log the exception stack trace and return error case view response
logger.error('...')
return render_to_response('user friendly error message etc.')
I would like to extract the "try" except block to a decorator. So I wrote something like the following:
import logging.config
logging.config.fileConfig(LOGGING_CONFIG_FILE)
logger = logging.getLogger(__name__)
def decorator(view):
def inner(*args, **kwargs):
try:
return view(*args, **kwargs)
except:
exception_traceback = traceback.format_exc(5)
error_message = 'Exception:%s' % exception_traceback
print 'Unexpected error occurred: %s' %(exception_traceback)
logger.error( 'Unexpected error occurred: %s' %(exception_traceback))
return render_to_response('error.json',
{
'message': 'Unexpected system error occured - please contact system administrator'
},
mimetype='text/plain')
return inner
Assume that normally I return a json in case of success as well.
For some reason my logging message does not show up in the file. The "print" message in the except clause shows up in the console. If I use a logging message in the view itself, it shows up so the logging configuration is ok. I must be missing something simple if anyone can point that out, would appreciate it!
Thanx!
Posting the logging config file:
[loggers]
keys=root
[logger_root]
handlers=screen,file
level=DEBUG
[formatters]
keys=simple,complex
[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
[formatter_complex]
format=%(asctime)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s
[handlers]
keys=file,screen
[handler_file]
class=handlers.RotatingFileHandler
formatter=complex
level=DEBUG
args=('/tmp/rule150/logs/rule150.log','a',1000000,5)
[handler_screen]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)
Upvotes: 4
Views: 1897
Reputation: 99385
Don't call fileConfig
in your views: do this in settings.py
, as recommended in my answer to another question. Your view code should only contain the code to define the logger (as you already have it) as well as the logging calls themselves. Post your findings once you've made this change.
Also, don't post comments to your own questions. You should be able to edit your question to e.g. add the logging config file, and be able to format it better than you can in a comment.
Upvotes: 1