http_logging.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """ASGI response logging outside authentication, without consuming request bodies."""
  2. import logging
  3. import time
  4. from uuid import uuid4
  5. from starlette.responses import PlainTextResponse
  6. from .logging_setup import request_context
  7. logger = logging.getLogger(__name__)
  8. class RequestLoggingMiddleware:
  9. def __init__(self, app):
  10. self.app = app
  11. async def __call__(self, scope, receive, send):
  12. if scope['type'] != 'http':
  13. return await self.app(scope, receive, send)
  14. request_id = uuid4().hex
  15. scope.setdefault('state', {})['request_id'] = request_id
  16. token = request_context.set({'request_id': request_id, 'scope': scope})
  17. started = time.perf_counter()
  18. status, completed, failed = None, False, False
  19. def finish(outcome, level=None):
  20. nonlocal completed
  21. if completed: return
  22. completed = True
  23. level = level or (logging.ERROR if status and status >= 500 else logging.WARNING if status and status >= 400 else
  24. logging.DEBUG if scope['path'] == '/health' or scope['path'].startswith('/static/') else logging.INFO)
  25. logger.log(level, 'HTTP-Anfrage abgeschlossen', extra={
  26. 'event': 'http_completed', 'status': status,
  27. 'duration_ms': round((time.perf_counter()-started)*1000, 2), 'outcome': outcome,
  28. })
  29. async def logged_send(message):
  30. nonlocal status
  31. if message['type'] == 'http.response.start':
  32. message = dict(message, headers=[(key, value) for key, value in message.get('headers', [])
  33. if key.lower() != b'x-request-id'] + [(b'x-request-id', request_id.encode('ascii'))])
  34. await send(message)
  35. if message['type'] == 'http.response.start': status = message['status']
  36. if message['type'] == 'http.response.body' and not message.get('more_body', False):
  37. finish('completed')
  38. try:
  39. await self.app(scope, receive, logged_send)
  40. except Exception:
  41. failed = True
  42. streaming = status is not None
  43. logger.exception('HTTP-Verarbeitung fehlgeschlagen', extra={'event': 'response_stream_error' if streaming else 'unhandled_exception'})
  44. if status is None: status = 500
  45. if not completed:
  46. finish('stream_failed' if streaming else 'failed', logging.ERROR)
  47. raise
  48. finally:
  49. if not completed and not failed: finish('aborted', logging.WARNING)
  50. request_context.reset(token)
  51. async def unhandled_error_response(request, exc):
  52. request_id = getattr(request.state, 'request_id', None)
  53. return PlainTextResponse('Internal Server Error', status_code=500,
  54. headers={'X-Request-ID': request_id} if request_id else {})
  55. def install_request_logging(app):
  56. app.add_middleware(RequestLoggingMiddleware)
  57. app.add_exception_handler(Exception, unhandled_error_response)