log.py 6.8 KB

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