log.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. # Copyright © 2017-2023 Unrud <unrud@outlook.com>
  4. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Functions to set up Python's logging facility for Radicale's WSGI application.
  20. Log messages are sent to the first available target of:
  21. - Error stream specified by the WSGI server in "wsgi.errors"
  22. - ``sys.stderr``
  23. """
  24. import contextlib
  25. import io
  26. import logging
  27. import os
  28. import socket
  29. import struct
  30. import sys
  31. import threading
  32. import time
  33. from typing import (Any, Callable, ClassVar, Dict, Iterator, Mapping, Optional,
  34. Tuple, Union, cast)
  35. from radicale import types
  36. LOGGER_NAME: str = "radicale"
  37. LOGGER_FORMATS: Mapping[str, str] = {
  38. "verbose": "[%(asctime)s] [%(ident)s] [%(levelname)s] %(message)s",
  39. "journal": "[%(ident)s] [%(levelname)s] %(message)s",
  40. }
  41. DATE_FORMAT: str = "%Y-%m-%d %H:%M:%S %z"
  42. logger: logging.Logger = logging.getLogger(LOGGER_NAME)
  43. class RemoveTracebackFilter(logging.Filter):
  44. def filter(self, record: logging.LogRecord) -> bool:
  45. record.exc_info = None
  46. return True
  47. REMOVE_TRACEBACK_FILTER: logging.Filter = RemoveTracebackFilter()
  48. class IdentLogRecordFactory:
  49. """LogRecordFactory that adds ``ident`` attribute."""
  50. def __init__(self, upstream_factory: Callable[..., logging.LogRecord]
  51. ) -> None:
  52. self._upstream_factory = upstream_factory
  53. def __call__(self, *args: Any, **kwargs: Any) -> logging.LogRecord:
  54. record = self._upstream_factory(*args, **kwargs)
  55. ident = ("%d" % record.process if record.process is not None
  56. else record.processName or "unknown")
  57. tid = None
  58. if record.thread is not None:
  59. if record.thread != threading.main_thread().ident:
  60. ident += "/%s" % (record.threadName or "unknown")
  61. if (sys.version_info >= (3, 8) and
  62. record.thread == threading.get_ident()):
  63. try:
  64. tid = threading.get_native_id()
  65. except AttributeError:
  66. # so far function not existing e.g. on SunOS
  67. # see also https://docs.python.org/3/library/threading.html#threading.get_native_id
  68. tid = None
  69. record.ident = ident # type:ignore[attr-defined]
  70. record.tid = tid # type:ignore[attr-defined]
  71. return record
  72. class ThreadedStreamHandler(logging.Handler):
  73. """Sends logging output to the stream registered for the current thread or
  74. ``sys.stderr`` when no stream was registered."""
  75. terminator: ClassVar[str] = "\n"
  76. _streams: Dict[int, types.ErrorStream]
  77. _journal_stream_id: Optional[Tuple[int, int]]
  78. _journal_socket: Optional[socket.socket]
  79. _journal_socket_failed: bool
  80. _formatters: Mapping[str, logging.Formatter]
  81. _formatter: Optional[logging.Formatter]
  82. def __init__(self, format_name: Optional[str] = None) -> None:
  83. super().__init__()
  84. self._streams = {}
  85. self._journal_stream_id = None
  86. with contextlib.suppress(TypeError, ValueError):
  87. dev, inode = os.environ.get("JOURNAL_STREAM", "").split(":", 1)
  88. self._journal_stream_id = (int(dev), int(inode))
  89. self._journal_socket = None
  90. self._journal_socket_failed = False
  91. self._formatters = {name: logging.Formatter(fmt, DATE_FORMAT)
  92. for name, fmt in LOGGER_FORMATS.items()}
  93. self._formatter = (self._formatters[format_name]
  94. if format_name is not None else None)
  95. def _get_formatter(self, default_format_name: str) -> logging.Formatter:
  96. return self._formatter or self._formatters[default_format_name]
  97. def _detect_journal(self, stream: types.ErrorStream) -> bool:
  98. if not self._journal_stream_id or not isinstance(stream, io.IOBase):
  99. return False
  100. try:
  101. stat = os.fstat(stream.fileno())
  102. except OSError:
  103. return False
  104. return self._journal_stream_id == (stat.st_dev, stat.st_ino)
  105. @staticmethod
  106. def _encode_journal(data: Mapping[str, Optional[Union[str, int]]]
  107. ) -> bytes:
  108. msg = b""
  109. for key, value in data.items():
  110. if value is None:
  111. continue
  112. keyb = key.encode()
  113. valueb = str(value).encode()
  114. if b"\n" in valueb:
  115. msg += (keyb + b"\n" +
  116. struct.pack("<Q", len(valueb)) + valueb + b"\n")
  117. else:
  118. msg += keyb + b"=" + valueb + b"\n"
  119. return msg
  120. def _try_emit_journal(self, record: logging.LogRecord) -> bool:
  121. if not self._journal_socket:
  122. # Try to connect to systemd journal socket
  123. if self._journal_socket_failed or not hasattr(socket, "AF_UNIX"):
  124. return False
  125. journal_socket = None
  126. try:
  127. journal_socket = socket.socket(
  128. socket.AF_UNIX, socket.SOCK_DGRAM)
  129. journal_socket.connect("/run/systemd/journal/socket")
  130. except OSError as e:
  131. self._journal_socket_failed = True
  132. if journal_socket:
  133. journal_socket.close()
  134. # Log after setting `_journal_socket_failed` to prevent loop!
  135. logger.error("Failed to connect to systemd journal: %s",
  136. e, exc_info=True)
  137. return False
  138. self._journal_socket = journal_socket
  139. priority = {"DEBUG": 7,
  140. "INFO": 6,
  141. "WARNING": 4,
  142. "ERROR": 3,
  143. "CRITICAL": 2}.get(record.levelname, 4)
  144. timestamp = time.strftime("%Y-%m-%dT%H:%M:%S.%%03dZ",
  145. time.gmtime(record.created)) % record.msecs
  146. data = {"PRIORITY": priority,
  147. "TID": cast(Optional[int], getattr(record, "tid", None)),
  148. "SYSLOG_IDENTIFIER": record.name,
  149. "SYSLOG_FACILITY": 1,
  150. "SYSLOG_PID": record.process,
  151. "SYSLOG_TIMESTAMP": timestamp,
  152. "CODE_FILE": record.pathname,
  153. "CODE_LINE": record.lineno,
  154. "CODE_FUNC": record.funcName,
  155. "MESSAGE": self._get_formatter("journal").format(record)}
  156. self._journal_socket.sendall(self._encode_journal(data))
  157. return True
  158. def emit(self, record: logging.LogRecord) -> None:
  159. try:
  160. stream = self._streams.get(threading.get_ident(), sys.stderr)
  161. if self._detect_journal(stream) and self._try_emit_journal(record):
  162. return
  163. msg = self._get_formatter("verbose").format(record)
  164. stream.write(msg + self.terminator)
  165. stream.flush()
  166. except Exception:
  167. self.handleError(record)
  168. @types.contextmanager
  169. def register_stream(self, stream: types.ErrorStream) -> Iterator[None]:
  170. """Register stream for logging output of the current thread."""
  171. key = threading.get_ident()
  172. self._streams[key] = stream
  173. try:
  174. yield
  175. finally:
  176. del self._streams[key]
  177. @types.contextmanager
  178. def register_stream(stream: types.ErrorStream) -> Iterator[None]:
  179. """Register stream for logging output of the current thread."""
  180. yield
  181. def setup() -> None:
  182. """Set global logging up."""
  183. global register_stream
  184. format_name = os.environ.get("RADICALE_LOG_FORMAT") or None
  185. sane_format_name = format_name if format_name in LOGGER_FORMATS else None
  186. handler = ThreadedStreamHandler(sane_format_name)
  187. logging.basicConfig(handlers=[handler])
  188. register_stream = handler.register_stream
  189. log_record_factory = IdentLogRecordFactory(logging.getLogRecordFactory())
  190. logging.setLogRecordFactory(log_record_factory)
  191. set_level(logging.INFO, True)
  192. if format_name != sane_format_name:
  193. logger.error("Invalid RADICALE_LOG_FORMAT: %r", format_name)
  194. logger_display_backtrace_disabled: bool = False
  195. logger_display_backtrace_enabled: bool = False
  196. def set_level(level: Union[int, str], backtrace_on_debug: bool) -> None:
  197. """Set logging level for global logger."""
  198. global logger_display_backtrace_disabled
  199. global logger_display_backtrace_enabled
  200. if isinstance(level, str):
  201. level = getattr(logging, level.upper())
  202. assert isinstance(level, int)
  203. logger.setLevel(level)
  204. if level > logging.DEBUG:
  205. if logger_display_backtrace_disabled is False:
  206. logger.info("Logging of backtrace is disabled in this loglevel")
  207. logger_display_backtrace_disabled = True
  208. logger.addFilter(REMOVE_TRACEBACK_FILTER)
  209. else:
  210. if not backtrace_on_debug:
  211. if logger_display_backtrace_disabled is False:
  212. logger.debug("Logging of backtrace is disabled by option in this loglevel")
  213. logger_display_backtrace_disabled = True
  214. logger.addFilter(REMOVE_TRACEBACK_FILTER)
  215. else:
  216. if logger_display_backtrace_enabled is False:
  217. logger.debug("Logging of backtrace is enabled by option in this loglevel")
  218. logger_display_backtrace_enabled = True
  219. logger.removeFilter(REMOVE_TRACEBACK_FILTER)