logging.py 2.2 KB

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