Last active
November 29, 2020 00:53
-
-
Save Karmak23/2ea1d62ea32edbeed07b to your computer and use it in GitHub Desktop.
Django Rest Framework logger mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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