log.py 8.4 KB

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