log.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. tid = threading.get_native_id()
  64. record.ident = ident # type:ignore[attr-defined]
  65. record.tid = tid # type:ignore[attr-defined]
  66. return record
  67. class ThreadedStreamHandler(logging.Handler):
  68. """Sends logging output to the stream registered for the current thread or
  69. ``sys.stderr`` when no stream was registered."""
  70. terminator: ClassVar[str] = "\n"
  71. _streams: Dict[int, types.ErrorStream]
  72. _journal_stream_id: Optional[Tuple[int, int]]
  73. _journal_socket: Optional[socket.socket]
  74. _journal_socket_failed: bool
  75. _formatters: Mapping[str, logging.Formatter]
  76. _formatter: Optional[logging.Formatter]
  77. def __init__(self, format_name: Optional[str] = None) -> None:
  78. super().__init__()
  79. self._streams = {}
  80. self._journal_stream_id = None
  81. with contextlib.suppress(TypeError, ValueError):
  82. dev, inode = os.environ.get("JOURNAL_STREAM", "").split(":", 1)
  83. self._journal_stream_id = (int(dev), int(inode))
  84. self._journal_socket = None
  85. self._journal_socket_failed = False
  86. self._formatters = {name: logging.Formatter(fmt, DATE_FORMAT)
  87. for name, fmt in LOGGER_FORMATS.items()}
  88. self._formatter = (self._formatters[format_name]
  89. if format_name is not None else None)
  90. def _get_formatter(self, default_format_name: str) -> logging.Formatter:
  91. return self._formatter or self._formatters[default_format_name]
  92. def _detect_journal(self, stream: types.ErrorStream) -> bool:
  93. if not self._journal_stream_id or not isinstance(stream, io.IOBase):
  94. return False
  95. try:
  96. stat = os.fstat(stream.fileno())
  97. except OSError:
  98. return False
  99. return self._journal_stream_id == (stat.st_dev, stat.st_ino)
  100. @staticmethod
  101. def _encode_journal(data: Mapping[str, Optional[Union[str, int]]]
  102. ) -> bytes:
  103. msg = b""
  104. for key, value in data.items():
  105. if value is None:
  106. continue
  107. keyb = key.encode()
  108. valueb = str(value).encode()
  109. if b"\n" in valueb:
  110. msg += (keyb + b"\n" +
  111. struct.pack("<Q", len(valueb)) + valueb + b"\n")
  112. else:
  113. msg += keyb + b"=" + valueb + b"\n"
  114. return msg
  115. def _try_emit_journal(self, record: logging.LogRecord) -> bool:
  116. if not self._journal_socket:
  117. # Try to connect to systemd journal socket
  118. if self._journal_socket_failed or not hasattr(socket, "AF_UNIX"):
  119. return False
  120. journal_socket = None
  121. try:
  122. journal_socket = socket.socket(
  123. socket.AF_UNIX, socket.SOCK_DGRAM)
  124. journal_socket.connect("/run/systemd/journal/socket")
  125. except OSError as e:
  126. self._journal_socket_failed = True
  127. if journal_socket:
  128. journal_socket.close()
  129. # Log after setting `_journal_socket_failed` to prevent loop!
  130. logger.error("Failed to connect to systemd journal: %s",
  131. e, exc_info=True)
  132. return False
  133. self._journal_socket = journal_socket
  134. priority = {"DEBUG": 7,
  135. "INFO": 6,
  136. "WARNING": 4,
  137. "ERROR": 3,
  138. "CRITICAL": 2}.get(record.levelname, 4)
  139. timestamp = time.strftime("%Y-%m-%dT%H:%M:%S.%%03dZ",
  140. time.gmtime(record.created)) % record.msecs
  141. data = {"PRIORITY": priority,
  142. "TID": cast(Optional[int], getattr(record, "tid", None)),
  143. "SYSLOG_IDENTIFIER": record.name,
  144. "SYSLOG_FACILITY": 1,
  145. "SYSLOG_PID": record.process,
  146. "SYSLOG_TIMESTAMP": timestamp,
  147. "CODE_FILE": record.pathname,
  148. "CODE_LINE": record.lineno,
  149. "CODE_FUNC": record.funcName,
  150. "MESSAGE": self._get_formatter("journal").format(record)}
  151. self._journal_socket.sendall(self._encode_journal(data))
  152. return True
  153. def emit(self, record: logging.LogRecord) -> None:
  154. try:
  155. stream = self._streams.get(threading.get_ident(), sys.stderr)
  156. if self._detect_journal(stream) and self._try_emit_journal(record):
  157. return
  158. msg = self._get_formatter("verbose").format(record)
  159. stream.write(msg + self.terminator)
  160. stream.flush()
  161. except Exception:
  162. self.handleError(record)
  163. @types.contextmanager
  164. def register_stream(self, stream: types.ErrorStream) -> Iterator[None]:
  165. """Register stream for logging output of the current thread."""
  166. key = threading.get_ident()
  167. self._streams[key] = stream
  168. try:
  169. yield
  170. finally:
  171. del self._streams[key]
  172. @types.contextmanager
  173. def register_stream(stream: types.ErrorStream) -> Iterator[None]:
  174. """Register stream for logging output of the current thread."""
  175. yield
  176. def setup() -> None:
  177. """Set global logging up."""
  178. global register_stream
  179. format_name = os.environ.get("RADICALE_LOG_FORMAT") or None
  180. sane_format_name = format_name if format_name in LOGGER_FORMATS else None
  181. handler = ThreadedStreamHandler(sane_format_name)
  182. logging.basicConfig(handlers=[handler])
  183. register_stream = handler.register_stream
  184. log_record_factory = IdentLogRecordFactory(logging.getLogRecordFactory())
  185. logging.setLogRecordFactory(log_record_factory)
  186. set_level(logging.INFO, True)
  187. if format_name != sane_format_name:
  188. logger.error("Invalid RADICALE_LOG_FORMAT: %r", format_name)
  189. def set_level(level: Union[int, str], backtrace_on_debug: bool) -> None:
  190. """Set logging level for global logger."""
  191. if isinstance(level, str):
  192. level = getattr(logging, level.upper())
  193. assert isinstance(level, int)
  194. logger.setLevel(level)
  195. if level > logging.DEBUG:
  196. logger.info("Logging of backtrace is disabled in this loglevel")
  197. logger.addFilter(REMOVE_TRACEBACK_FILTER)
  198. else:
  199. if not backtrace_on_debug:
  200. logger.debug("Logging of backtrace is disabled by option in this loglevel")
  201. logger.addFilter(REMOVE_TRACEBACK_FILTER)
  202. else:
  203. logger.removeFilter(REMOVE_TRACEBACK_FILTER)