1👍
All you need to do is to use Python’s logging framework to raise an appropriate message at the appropriate level. In your settings.py
there is a LOGGING
variable that defines how things are logged. By default I believe Django has any ERROR
in django.request
will be handled by mail_admins
.
So in your code, all you need to do is
import logging
logger = logging.getLogger(__name__) # this will create a logger with the module being the logger name
try:
#do stuff you watch to catch
except:
# we're going to catch and just log it
logger.error('Some error title', exc_info=True) # exc_info=True will include the stacktrace
finally:
# what you want to do in your finally block.
Note, this will swallow the exception and won’t bubble it up. Your response will return as a 200. If you want to bubble up the exception, just call raise
in your except
block. However, if all you care about is logging the error, but the view is still functional, then just log and swallow it.
In your LOGGING
variable, you can add additional entries to loggers for the different logger names. You can have an app log at a different logging status, say INFO
if you want to debug a certain code path. As long as you create a logger with the module name, you have a lot of flexibility of segmenting your logging to different handlers such as mail_admins.
Lastly, I’d recommend to look into sentry, as it’s a really great error logging tool.