log.py 8.6 KB

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