admin / Synapse-Cortex
publicSelf Hosted ITSM Tool with RBAC/Tenanting and MFA
Synapse-Cortex / synapse-cortex / .venv / Lib / site-packages / sqlalchemy / log.py
8895 B · main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | # log.py # Copyright (C) 2006-2024 the SQLAlchemy authors and contributors # <see AUTHORS file> # Includes alterations by Vinay Sajip [email protected] # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """Logging control and utilities. Control of logging for SA can be performed from the regular python logging module. The regular dotted module namespace is used, starting at 'sqlalchemy'. For class-level logging, the class name is appended. The "echo" keyword parameter, available on SQLA :class:`_engine.Engine` and :class:`_pool.Pool` objects, corresponds to a logger specific to that instance only. """ from __future__ import annotations import logging import sys from typing import Any from typing import Optional from typing import overload from typing import Set from typing import Type from typing import TypeVar from typing import Union from .util import py311 from .util import py38 from .util.typing import Literal if py38: STACKLEVEL = True # needed as of py3.11.0b1 # #8019 STACKLEVEL_OFFSET = 2 if py311 else 1 else: STACKLEVEL = False STACKLEVEL_OFFSET = 0 _IT = TypeVar("_IT", bound="Identified") _EchoFlagType = Union[None, bool, Literal["debug"]] # set initial level to WARN. This so that # log statements don't occur in the absence of explicit # logging being enabled for 'sqlalchemy'. rootlogger = logging.getLogger("sqlalchemy") if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN) def _add_default_handler(logger: logging.Logger) -> None: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s") ) logger.addHandler(handler) _logged_classes: Set[Type[Identified]] = set() def _qual_logger_name_for_cls(cls: Type[Identified]) -> str: return ( getattr(cls, "_sqla_logger_namespace", None) or cls.__module__ + "." + cls.__name__ ) def class_logger(cls: Type[_IT]) -> Type[_IT]: logger = logging.getLogger(_qual_logger_name_for_cls(cls)) cls._should_log_debug = lambda self: logger.isEnabledFor( # type: ignore[method-assign] # noqa: E501 logging.DEBUG ) cls._should_log_info = lambda self: logger.isEnabledFor( # type: ignore[method-assign] # noqa: E501 logging.INFO ) cls.logger = logger _logged_classes.add(cls) return cls _IdentifiedLoggerType = Union[logging.Logger, "InstanceLogger"] class Identified: __slots__ = () logging_name: Optional[str] = None logger: _IdentifiedLoggerType _echo: _EchoFlagType def _should_log_debug(self) -> bool: return self.logger.isEnabledFor(logging.DEBUG) def _should_log_info(self) -> bool: return self.logger.isEnabledFor(logging.INFO) class InstanceLogger: """A logger adapter (wrapper) for :class:`.Identified` subclasses. This allows multiple instances (e.g. Engine or Pool instances) to share a logger, but have its verbosity controlled on a per-instance basis. The basic functionality is to return a logging level which is based on an instance's echo setting. Default implementation is: 'debug' -> logging.DEBUG True -> logging.INFO False -> Effective level of underlying logger ( logging.WARNING by default) None -> same as False """ # Map echo settings to logger levels _echo_map = { None: logging.NOTSET, False: logging.NOTSET, True: logging.INFO, "debug": logging.DEBUG, } _echo: _EchoFlagType __slots__ = ("echo", "logger") def __init__(self, echo: _EchoFlagType, name: str): self.echo = echo self.logger = logging.getLogger(name) # if echo flag is enabled and no handlers, # add a handler to the list if self._echo_map[echo] <= logging.INFO and not self.logger.handlers: _add_default_handler(self.logger) # # Boilerplate convenience methods # def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: """Delegate a debug call to the underlying logger.""" self.log(logging.DEBUG, msg, *args, **kwargs) def info(self, msg: str, *args: Any, **kwargs: Any) -> None: """Delegate an info call to the underlying logger.""" self.log(logging.INFO, msg, *args, **kwargs) def warning(self, msg: str, *args: Any, **kwargs: Any) -> None: """Delegate a warning call to the underlying logger.""" self.log(logging.WARNING, msg, *args, **kwargs) warn = warning def error(self, msg: str, *args: Any, **kwargs: Any) -> None: """ Delegate an error call to the underlying logger. """ self.log(logging.ERROR, msg, *args, **kwargs) def exception(self, msg: str, *args: Any, **kwargs: Any) -> None: """Delegate an exception call to the underlying logger.""" kwargs["exc_info"] = 1 self.log(logging.ERROR, msg, *args, **kwargs) def critical(self, msg: str, *args: Any, **kwargs: Any) -> None: """Delegate a critical call to the underlying logger.""" self.log(logging.CRITICAL, msg, *args, **kwargs) def log(self, level: int, msg: str, *args: Any, **kwargs: Any) -> None: """Delegate a log call to the underlying logger. The level here is determined by the echo flag as well as that of the underlying logger, and logger._log() is called directly. """ # inline the logic from isEnabledFor(), # getEffectiveLevel(), to avoid overhead. if self.logger.manager.disable >= level: return selected_level = self._echo_map[self.echo] if selected_level == logging.NOTSET: selected_level = self.logger.getEffectiveLevel() if level >= selected_level: if STACKLEVEL: kwargs["stacklevel"] = ( kwargs.get("stacklevel", 1) + STACKLEVEL_OFFSET ) self.logger._log(level, msg, args, **kwargs) def isEnabledFor(self, level: int) -> bool: """Is this logger enabled for level 'level'?""" if self.logger.manager.disable >= level: return False return level >= self.getEffectiveLevel() def getEffectiveLevel(self) -> int: """What's the effective level for this logger?""" level = self._echo_map[self.echo] if level == logging.NOTSET: level = self.logger.getEffectiveLevel() return level def instance_logger( instance: Identified, echoflag: _EchoFlagType = None ) -> None: """create a logger for an instance that implements :class:`.Identified`.""" if instance.logging_name: name = "%s.%s" % ( _qual_logger_name_for_cls(instance.__class__), instance.logging_name, ) else: name = _qual_logger_name_for_cls(instance.__class__) instance._echo = echoflag # type: ignore logger: Union[logging.Logger, InstanceLogger] if echoflag in (False, None): # if no echo setting or False, return a Logger directly, # avoiding overhead of filtering logger = logging.getLogger(name) else: # if a specified echo flag, return an EchoLogger, # which checks the flag, overrides normal log # levels by calling logger._log() logger = InstanceLogger(echoflag, name) instance.logger = logger # type: ignore class echo_property: __doc__ = """\ When ``True``, enable log output for this element. This has the effect of setting the Python logging level for the namespace of this element's class and object reference. A value of boolean ``True`` indicates that the loglevel ``logging.INFO`` will be set for the logger, whereas the string value ``debug`` will set the loglevel to ``logging.DEBUG``. """ @overload def __get__( self, instance: Literal[None], owner: Type[Identified] ) -> echo_property: ... @overload def __get__( self, instance: Identified, owner: Type[Identified] ) -> _EchoFlagType: ... def __get__( self, instance: Optional[Identified], owner: Type[Identified] ) -> Union[echo_property, _EchoFlagType]: if instance is None: return self else: return instance._echo def __set__(self, instance: Identified, value: _EchoFlagType) -> None: instance_logger(instance, echoflag=value) |