You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.7 KiB

4 years ago
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) Jupyter Development Team
  3. #
  4. # Distributed under the terms of the BSD License. The full license is in
  5. # the file COPYING, distributed as part of this software.
  6. #-----------------------------------------------------------------------------
  7. import json
  8. from tornado.log import access_log
  9. from .metrics import prometheus_log_method
  10. def log_request(handler):
  11. """log a bit more information about each request than tornado's default
  12. - move static file get success to debug-level (reduces noise)
  13. - get proxied IP instead of proxy IP
  14. - log referer for redirect and failed requests
  15. - log user-agent for failed requests
  16. """
  17. status = handler.get_status()
  18. request = handler.request
  19. if status < 300 or status == 304:
  20. # Successes (or 304 FOUND) are debug-level
  21. log_method = access_log.debug
  22. elif status < 400:
  23. log_method = access_log.info
  24. elif status < 500:
  25. log_method = access_log.warning
  26. else:
  27. log_method = access_log.error
  28. request_time = 1000.0 * handler.request.request_time()
  29. ns = dict(
  30. status=status,
  31. method=request.method,
  32. ip=request.remote_ip,
  33. uri=request.uri,
  34. request_time=request_time,
  35. )
  36. msg = "{status} {method} {uri} ({ip}) {request_time:.2f}ms"
  37. if status >= 400:
  38. # log bad referers
  39. ns['referer'] = request.headers.get('Referer', 'None')
  40. msg = msg + ' referer={referer}'
  41. if status >= 500 and status != 502:
  42. # log all headers if it caused an error
  43. log_method(json.dumps(dict(request.headers), indent=2))
  44. log_method(msg.format(**ns))
  45. prometheus_log_method(handler)