-
-
Save danpalmer/16cdd5aa2941fa9706a44bb28c54729b to your computer and use it in GitHub Desktop.
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 StructuredLoggingMiddleware(object): | |
def __init__(self, get_response): | |
self.get_response = get_response | |
self.logger = structlog.getLogger('django') | |
def __call__(self, request): | |
from ipware import get_client_ip | |
request_id = str(uuid.uuid4()) | |
with structlog.threadlocal.tmp_bind(self.logger): | |
self.logger.bind(request_id=request_id) | |
if hasattr(request, "user"): | |
self.logger.bind(user_id=request.user.pk) | |
ip, routable = get_client_ip(request) | |
self.logger.bind(ip=ip) | |
self._did_error = False | |
self.logger.info( | |
"request_started", | |
request=request, | |
user_agent=request.META.get("HTTP_USER_AGENT"), | |
) | |
response = self.get_response(request) | |
if not self._did_error: | |
self.logger.info( | |
"request_finished", | |
code=response.status_code, | |
request=request, | |
) | |
return response | |
def process_exception(self, request, exception): | |
if isinstance(exception, Http404): | |
# We don't log an exception here, and we don't set that we handled | |
# an error as we want the standard `request_finished` log message | |
# to be emitted. | |
return | |
self._did_error = True | |
self.logger.exception( | |
"request_failed", | |
code=500, | |
request=request, | |
exc_info=exception, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I use the kwargs
exc_info
orexception
these metadata will not appear in the log. I think they are reserved words.