log.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. # log.py
  2. # Copyright (C) 2006-2024 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: https://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.Engine`
  13. and :class:`_pool.Pool` objects, corresponds to a logger specific to that
  14. instance only.
  15. """
  16. import logging
  17. import sys
  18. from .util import py311
  19. from .util import py38
  20. if py38:
  21. STACKLEVEL = True
  22. # needed as of py3.11.0b1
  23. # #8019
  24. STACKLEVEL_OFFSET = 2 if py311 else 1
  25. else:
  26. STACKLEVEL = False
  27. STACKLEVEL_OFFSET = 0
  28. # set initial level to WARN. This so that
  29. # log statements don't occur in the absence of explicit
  30. # logging being enabled for 'sqlalchemy'.
  31. rootlogger = logging.getLogger("sqlalchemy")
  32. if rootlogger.level == logging.NOTSET:
  33. rootlogger.setLevel(logging.WARN)
  34. def _add_default_handler(logger):
  35. handler = logging.StreamHandler(sys.stdout)
  36. handler.setFormatter(
  37. logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
  38. )
  39. logger.addHandler(handler)
  40. _logged_classes = set()
  41. def _qual_logger_name_for_cls(cls):
  42. return (
  43. getattr(cls, "_sqla_logger_namespace", None)
  44. or cls.__module__ + "." + cls.__name__
  45. )
  46. def class_logger(cls):
  47. logger = logging.getLogger(_qual_logger_name_for_cls(cls))
  48. cls._should_log_debug = lambda self: logger.isEnabledFor(logging.DEBUG)
  49. cls._should_log_info = lambda self: logger.isEnabledFor(logging.INFO)
  50. cls.logger = logger
  51. _logged_classes.add(cls)
  52. return cls
  53. class Identified(object):
  54. logging_name = None
  55. def _should_log_debug(self):
  56. return self.logger.isEnabledFor(logging.DEBUG)
  57. def _should_log_info(self):
  58. return self.logger.isEnabledFor(logging.INFO)
  59. class InstanceLogger(object):
  60. """A logger adapter (wrapper) for :class:`.Identified` subclasses.
  61. This allows multiple instances (e.g. Engine or Pool instances)
  62. to share a logger, but have its verbosity controlled on a
  63. per-instance basis.
  64. The basic functionality is to return a logging level
  65. which is based on an instance's echo setting.
  66. Default implementation is:
  67. 'debug' -> logging.DEBUG
  68. True -> logging.INFO
  69. False -> Effective level of underlying logger (
  70. logging.WARNING by default)
  71. None -> same as False
  72. """
  73. # Map echo settings to logger levels
  74. _echo_map = {
  75. None: logging.NOTSET,
  76. False: logging.NOTSET,
  77. True: logging.INFO,
  78. "debug": logging.DEBUG,
  79. }
  80. def __init__(self, echo, name):
  81. self.echo = echo
  82. self.logger = logging.getLogger(name)
  83. # if echo flag is enabled and no handlers,
  84. # add a handler to the list
  85. if self._echo_map[echo] <= logging.INFO and not self.logger.handlers:
  86. _add_default_handler(self.logger)
  87. #
  88. # Boilerplate convenience methods
  89. #
  90. def debug(self, msg, *args, **kwargs):
  91. """Delegate a debug call to the underlying logger."""
  92. self.log(logging.DEBUG, msg, *args, **kwargs)
  93. def info(self, msg, *args, **kwargs):
  94. """Delegate an info call to the underlying logger."""
  95. self.log(logging.INFO, msg, *args, **kwargs)
  96. def warning(self, msg, *args, **kwargs):
  97. """Delegate a warning call to the underlying logger."""
  98. self.log(logging.WARNING, msg, *args, **kwargs)
  99. warn = warning
  100. def error(self, msg, *args, **kwargs):
  101. """
  102. Delegate an error call to the underlying logger.
  103. """
  104. self.log(logging.ERROR, msg, *args, **kwargs)
  105. def exception(self, msg, *args, **kwargs):
  106. """Delegate an exception call to the underlying logger."""
  107. kwargs["exc_info"] = 1
  108. self.log(logging.ERROR, msg, *args, **kwargs)
  109. def critical(self, msg, *args, **kwargs):
  110. """Delegate a critical call to the underlying logger."""
  111. self.log(logging.CRITICAL, msg, *args, **kwargs)
  112. def log(self, level, msg, *args, **kwargs):
  113. """Delegate a log call to the underlying logger.
  114. The level here is determined by the echo
  115. flag as well as that of the underlying logger, and
  116. logger._log() is called directly.
  117. """
  118. # inline the logic from isEnabledFor(),
  119. # getEffectiveLevel(), to avoid overhead.
  120. if self.logger.manager.disable >= level:
  121. return
  122. selected_level = self._echo_map[self.echo]
  123. if selected_level == logging.NOTSET:
  124. selected_level = self.logger.getEffectiveLevel()
  125. if level >= selected_level:
  126. if STACKLEVEL:
  127. kwargs["stacklevel"] = (
  128. kwargs.get("stacklevel", 1) + STACKLEVEL_OFFSET
  129. )
  130. self.logger._log(level, msg, args, **kwargs)
  131. def isEnabledFor(self, level):
  132. """Is this logger enabled for level 'level'?"""
  133. if self.logger.manager.disable >= level:
  134. return False
  135. return level >= self.getEffectiveLevel()
  136. def getEffectiveLevel(self):
  137. """What's the effective level for this logger?"""
  138. level = self._echo_map[self.echo]
  139. if level == logging.NOTSET:
  140. level = self.logger.getEffectiveLevel()
  141. return level
  142. def instance_logger(instance, echoflag=None):
  143. """create a logger for an instance that implements :class:`.Identified`."""
  144. if instance.logging_name:
  145. name = "%s.%s" % (
  146. _qual_logger_name_for_cls(instance.__class__),
  147. instance.logging_name,
  148. )
  149. else:
  150. name = _qual_logger_name_for_cls(instance.__class__)
  151. instance._echo = echoflag
  152. if echoflag in (False, None):
  153. # if no echo setting or False, return a Logger directly,
  154. # avoiding overhead of filtering
  155. logger = logging.getLogger(name)
  156. else:
  157. # if a specified echo flag, return an EchoLogger,
  158. # which checks the flag, overrides normal log
  159. # levels by calling logger._log()
  160. logger = InstanceLogger(echoflag, name)
  161. instance.logger = logger
  162. class echo_property(object):
  163. __doc__ = """\
  164. When ``True``, enable log output for this element.
  165. This has the effect of setting the Python logging level for the namespace
  166. of this element's class and object reference. A value of boolean ``True``
  167. indicates that the loglevel ``logging.INFO`` will be set for the logger,
  168. whereas the string value ``debug`` will set the loglevel to
  169. ``logging.DEBUG``.
  170. """
  171. def __get__(self, instance, owner):
  172. if instance is None:
  173. return self
  174. else:
  175. return instance._echo
  176. def __set__(self, instance, value):
  177. instance_logger(instance, echoflag=value)