Skip to content

Instantly share code, notes, and snippets.

@vladimirmyshkovski
Forked from Karmak23/drf_logger.py
Created November 29, 2020 00:53
Show Gist options
  • Save vladimirmyshkovski/b351bf442cfedcbdd88fda1afa0ba461 to your computer and use it in GitHub Desktop.
Save vladimirmyshkovski/b351bf442cfedcbdd88fda1afa0ba461 to your computer and use it in GitHub Desktop.
Django Rest Framework logger mixin
class DRFLoggerMixin(object):
"""
Allows us to log any incoming request and to know what's in it.
Usage:
class MyOwnViewSet(DRFLoggerMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
pass
References:
http://stackoverflow.com/a/15579198/654755
Updates:
https://gist.github.com/Karmak23/2ea1d62ea32edbeed07b
"""
def initial(self, request, *args, **kwargs):
try:
data = request.DATA
except:
LOGGER.exception('Exception while getting request.DATA')
else:
try:
data = json.dumps(data, sort_keys=True, indent=2)
except:
pass
LOGGER.info(u'%(method)s request on “%(path)s” for %(user)s '
u'from %(origin)s (%(useragent)s):\n'
u'auth: %(auth)s, authenticators: [\n%(auths)s\n]\n'
u'content-type: %(content)s\n'
u'data: %(data)s\n'
u'files: {\n %(files)s\n}' % {
'method': request.method,
'user': request.user.username,
'path': request.get_full_path(),
'origin': request.META.get('HTTP_HOST', u'Unknown'),
'useragent': request.META.get('HTTP_USER_AGENT',
u'Unknown'),
'auth': request.auth,
'auths': u'\n '.join(
unicode(x) for x in request.authenticators),
'data': data,
'files': u'\n '.join(u'%s: %s' % (k,v)
for k,v in sorted(request.FILES.items())),
'content': request.content_type,
}
)
return super(DRFLoggerMixin, self).initial(request, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment