log.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # sqlalchemy/log.py
  2. # Copyright (C) 2006-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. # Includes alterations by Vinay Sajip vinay_sajip@yahoo.co.uk
  5. #
  6. # This module is part of SQLAlchemy and is released under
  7. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  8. """Logging control and utilities.
  9. Control of logging for SA can be performed from the regular python logging
  10. module. The regular dotted module namespace is used, starting at
  11. 'sqlalchemy'. For class-level logging, the class name is appended.
  12. The "echo" keyword parameter, available on SQLA :class:`.Engine`
  13. and :class:`.Pool` objects, corresponds to a logger specific to that
  14. instance only.
  15. """
  16. import logging
  17. import sys
  18. # set initial level to WARN. This so that
  19. # log statements don't occur in the absence of explicit
  20. # logging being enabled for 'sqlalchemy'.
  21. rootlogger = logging.getLogger('sqlalchemy')
  22. if rootlogger.level == logging.NOTSET:
  23. rootlogger.setLevel(logging.WARN)
  24. def _add_default_handler(logger):
  25. handler = logging.StreamHandler(sys.stdout)
  26. handler.setFormatter(logging.Formatter(
  27. '%(asctime)s %(levelname)s %(name)s %(message)s'))
  28. logger.addHandler(handler)
  29. _logged_classes = set()
  30. def class_logger(cls):
  31. logger = logging.getLogger(cls.__module__ + "." + cls.__name__)
  32. cls._should_log_debug = lambda self: logger.isEnabledFor(logging.DEBUG)
  33. cls._should_log_info = lambda self: logger.isEnabledFor(logging.INFO)
  34. cls.logger = logger
  35. _logged_classes.add(cls)
  36. return cls
  37. class Identified(object):
  38. logging_name = None
  39. def _should_log_debug(self):
  40. return self.logger.isEnabledFor(logging.DEBUG)
  41. def _should_log_info(self):
  42. return self.logger.isEnabledFor(logging.INFO)
  43. class InstanceLogger(object):
  44. """A logger adapter (wrapper) for :class:`.Identified` subclasses.
  45. This allows multiple instances (e.g. Engine or Pool instances)
  46. to share a logger, but have its verbosity controlled on a
  47. per-instance basis.
  48. The basic functionality is to return a logging level
  49. which is based on an instance's echo setting.
  50. Default implementation is:
  51. 'debug' -> logging.DEBUG
  52. True -> logging.INFO
  53. False -> Effective level of underlying logger
  54. (logging.WARNING by default)
  55. None -> same as False
  56. """
  57. # Map echo settings to logger levels
  58. _echo_map = {
  59. None: logging.NOTSET,
  60. False: logging.NOTSET,
  61. True: logging.INFO,
  62. 'debug': logging.DEBUG,
  63. }
  64. def __init__(self, echo, name):
  65. self.echo = echo
  66. self.logger = logging.getLogger(name)
  67. # if echo flag is enabled and no handlers,
  68. # add a handler to the list
  69. if self._echo_map[echo] <= logging.INFO \
  70. and not self.logger.handlers:
  71. _add_default_handler(self.logger)
  72. #
  73. # Boilerplate convenience methods
  74. #
  75. def debug(self, msg, *args, **kwargs):
  76. """Delegate a debug call to the underlying logger."""
  77. self.log(logging.DEBUG, msg, *args, **kwargs)
  78. def info(self, msg, *args, **kwargs):
  79. """Delegate an info call to the underlying logger."""
  80. self.log(logging.INFO, msg, *args, **kwargs)
  81. def warning(self, msg, *args, **kwargs):
  82. """Delegate a warning call to the underlying logger."""
  83. self.log(logging.WARNING, msg, *args, **kwargs)
  84. warn = warning
  85. def error(self, msg, *args, **kwargs):
  86. """
  87. Delegate an error call to the underlying logger.
  88. """
  89. self.log(logging.ERROR, msg, *args, **kwargs)
  90. def exception(self, msg, *args, **kwargs):
  91. """Delegate an exception call to the underlying logger."""
  92. kwargs["exc_info"] = 1
  93. self.log(logging.ERROR, msg, *args, **kwargs)
  94. def critical(self, msg, *args, **kwargs):
  95. """Delegate a critical call to the underlying logger."""
  96. self.log(logging.CRITICAL, msg, *args, **kwargs)
  97. def log(self, level, msg, *args, **kwargs):
  98. """Delegate a log call to the underlying logger.
  99. The level here is determined by the echo
  100. flag as well as that of the underlying logger, and
  101. logger._log() is called directly.
  102. """
  103. # inline the logic from isEnabledFor(),
  104. # getEffectiveLevel(), to avoid overhead.
  105. if self.logger.manager.disable >= level:
  106. return
  107. selected_level = self._echo_map[self.echo]
  108. if selected_level == logging.NOTSET:
  109. selected_level = self.logger.getEffectiveLevel()
  110. if level >= selected_level:
  111. self.logger._log(level, msg, args, **kwargs)
  112. def isEnabledFor(self, level):
  113. """Is this logger enabled for level 'level'?"""
  114. if self.logger.manager.disable >= level:
  115. return False
  116. return level >= self.getEffectiveLevel()
  117. def getEffectiveLevel(self):
  118. """What's the effective level for this logger?"""
  119. level = self._echo_map[self.echo]
  120. if level == logging.NOTSET:
  121. level = self.logger.getEffectiveLevel()
  122. return level
  123. def instance_logger(instance, echoflag=None):
  124. """create a logger for an instance that implements :class:`.Identified`."""
  125. if instance.logging_name:
  126. name = "%s.%s.%s" % (instance.__class__.__module__,
  127. instance.__class__.__name__,
  128. instance.logging_name)
  129. else:
  130. name = "%s.%s" % (instance.__class__.__module__,
  131. instance.__class__.__name__)
  132. instance._echo = echoflag
  133. if echoflag in (False, None):
  134. # if no echo setting or False, return a Logger directly,
  135. # avoiding overhead of filtering
  136. logger = logging.getLogger(name)
  137. else:
  138. # if a specified echo flag, return an EchoLogger,
  139. # which checks the flag, overrides normal log
  140. # levels by calling logger._log()
  141. logger = InstanceLogger(echoflag, name)
  142. instance.logger = logger
  143. class echo_property(object):
  144. __doc__ = """\
  145. When ``True``, enable log output for this element.
  146. This has the effect of setting the Python logging level for the namespace
  147. of this element's class and object reference. A value of boolean ``True``
  148. indicates that the loglevel ``logging.INFO`` will be set for the logger,
  149. whereas the string value ``debug`` will set the loglevel to
  150. ``logging.DEBUG``.
  151. """
  152. def __get__(self, instance, owner):
  153. if instance is None:
  154. return self
  155. else:
  156. return instance._echo
  157. def __set__(self, instance, value):
  158. instance_logger(instance, echoflag=value)