logging.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from __future__ import annotations
  2. import logging
  3. import sys
  4. import typing as t
  5. from werkzeug.local import LocalProxy
  6. from .globals import request
  7. if t.TYPE_CHECKING: # pragma: no cover
  8. from .sansio.app import App
  9. @LocalProxy
  10. def wsgi_errors_stream() -> t.TextIO:
  11. """Find the most appropriate error stream for the application. If a request
  12. is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.
  13. If you configure your own :class:`logging.StreamHandler`, you may want to
  14. use this for the stream. If you are using file or dict configuration and
  15. can't import this directly, you can refer to it as
  16. ``ext://flask.logging.wsgi_errors_stream``.
  17. """
  18. return request.environ["wsgi.errors"] if request else sys.stderr
  19. def has_level_handler(logger: logging.Logger) -> bool:
  20. """Check if there is a handler in the logging chain that will handle the
  21. given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.
  22. """
  23. level = logger.getEffectiveLevel()
  24. current = logger
  25. while current:
  26. if any(handler.level <= level for handler in current.handlers):
  27. return True
  28. if not current.propagate:
  29. break
  30. current = current.parent # type: ignore
  31. return False
  32. #: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format
  33. #: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.
  34. default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore
  35. default_handler.setFormatter(
  36. logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
  37. )
  38. def create_logger(app: App) -> logging.Logger:
  39. """Get the Flask app's logger and configure it if needed.
  40. The logger name will be the same as
  41. :attr:`app.import_name <flask.Flask.name>`.
  42. When :attr:`~flask.Flask.debug` is enabled, set the logger level to
  43. :data:`logging.DEBUG` if it is not set.
  44. If there is no handler for the logger's effective level, add a
  45. :class:`~logging.StreamHandler` for
  46. :func:`~flask.logging.wsgi_errors_stream` with a basic format.
  47. """
  48. logger = logging.getLogger(app.name)
  49. if app.debug and not logger.level:
  50. logger.setLevel(logging.DEBUG)
  51. if not has_level_handler(logger):
  52. logger.addHandler(default_handler)
  53. return logger