logging.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.logging
  4. ~~~~~~~~~~~~~
  5. Implements the logging support for Flask.
  6. :copyright: (c) 2011 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from __future__ import absolute_import
  10. from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG
  11. def create_logger(app):
  12. """Creates a logger for the given application. This logger works
  13. similar to a regular Python logger but changes the effective logging
  14. level based on the application's debug flag. Furthermore this
  15. function also removes all attached handlers in case there was a
  16. logger with the log name before.
  17. """
  18. Logger = getLoggerClass()
  19. class DebugLogger(Logger):
  20. def getEffectiveLevel(x):
  21. if x.level == 0 and app.debug:
  22. return DEBUG
  23. return Logger.getEffectiveLevel(x)
  24. class DebugHandler(StreamHandler):
  25. def emit(x, record):
  26. StreamHandler.emit(x, record) if app.debug else None
  27. handler = DebugHandler()
  28. handler.setLevel(DEBUG)
  29. handler.setFormatter(Formatter(app.debug_log_format))
  30. logger = getLogger(app.logger_name)
  31. # just in case that was not a new logger, get rid of all the handlers
  32. # already attached to it.
  33. del logger.handlers[:]
  34. logger.__class__ = DebugLogger
  35. logger.addHandler(handler)
  36. return logger