log.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. # Copyright © 2017-2018 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. Radicale logging module.
  19. Manage logging from a configuration file. For more information, see:
  20. http://docs.python.org/library/logging.config.html
  21. """
  22. import contextlib
  23. import io
  24. import logging
  25. import multiprocessing
  26. import os
  27. import sys
  28. import threading
  29. try:
  30. import systemd.journal
  31. except ImportError:
  32. systemd = None
  33. LOGGER_NAME = "radicale"
  34. LOGGER_FORMAT = "[%(ident)s] %(levelname)s: %(message)s"
  35. logger = logging.getLogger(LOGGER_NAME)
  36. class RemoveTracebackFilter(logging.Filter):
  37. def filter(self, record):
  38. record.exc_info = None
  39. return True
  40. removeTracebackFilter = RemoveTracebackFilter()
  41. class IdentLogRecordFactory:
  42. """LogRecordFactory that adds ``ident`` attribute."""
  43. def __init__(self, upstream_factory):
  44. self.upstream_factory = upstream_factory
  45. self.main_pid = os.getpid()
  46. def __call__(self, *args, **kwargs):
  47. record = self.upstream_factory(*args, **kwargs)
  48. pid = os.getpid()
  49. ident = "%x" % self.main_pid
  50. if pid != self.main_pid:
  51. ident += "%+x" % (pid - self.main_pid)
  52. main_thread = threading.main_thread()
  53. current_thread = threading.current_thread()
  54. if current_thread.name and main_thread != current_thread:
  55. ident += "/%s" % current_thread.name
  56. record.ident = ident
  57. return record
  58. class ThreadStreamsHandler(logging.Handler):
  59. terminator = "\n"
  60. def __init__(self, fallback_stream, fallback_handler):
  61. super().__init__()
  62. self._streams = {}
  63. self.fallback_stream = fallback_stream
  64. self.fallback_handler = fallback_handler
  65. def createLock(self):
  66. self.lock = multiprocessing.Lock()
  67. def setFormatter(self, form):
  68. super().setFormatter(form)
  69. self.fallback_handler.setFormatter(form)
  70. def emit(self, record):
  71. try:
  72. stream = self._streams.get(threading.get_ident())
  73. if stream is None:
  74. self.fallback_handler.emit(record)
  75. else:
  76. msg = self.format(record)
  77. stream.write(msg)
  78. stream.write(self.terminator)
  79. if hasattr(stream, "flush"):
  80. stream.flush()
  81. except Exception:
  82. self.handleError(record)
  83. @contextlib.contextmanager
  84. def register_stream(self, stream):
  85. if stream == self.fallback_stream:
  86. yield
  87. return
  88. key = threading.get_ident()
  89. self._streams[key] = stream
  90. try:
  91. yield
  92. finally:
  93. del self._streams[key]
  94. def get_default_handler():
  95. handler = logging.StreamHandler(sys.stderr)
  96. # Detect systemd journal
  97. with contextlib.suppress(ValueError, io.UnsupportedOperation):
  98. journal_dev, journal_ino = map(
  99. int, os.environ.get("JOURNAL_STREAM", "").split(":"))
  100. st = os.fstat(sys.stderr.fileno())
  101. if (systemd and
  102. st.st_dev == journal_dev and st.st_ino == journal_ino):
  103. handler = systemd.journal.JournalHandler(
  104. SYSLOG_IDENTIFIER=LOGGER_NAME)
  105. return handler
  106. @contextlib.contextmanager
  107. def register_stream(stream):
  108. """Register global errors stream for the current thread."""
  109. yield
  110. def setup():
  111. """Set global logging up."""
  112. global register_stream
  113. handler = ThreadStreamsHandler(sys.stderr, get_default_handler())
  114. logging.basicConfig(format=LOGGER_FORMAT, handlers=[handler])
  115. register_stream = handler.register_stream
  116. log_record_factory = IdentLogRecordFactory(logging.getLogRecordFactory())
  117. logging.setLogRecordFactory(log_record_factory)
  118. set_level(logging.DEBUG)
  119. def set_level(level):
  120. """Set logging level for global logger."""
  121. if isinstance(level, str):
  122. level = getattr(logging, level.upper())
  123. logger.setLevel(level)
  124. if level == logging.DEBUG:
  125. logger.removeFilter(removeTracebackFilter)
  126. else:
  127. logger.addFilter(removeTracebackFilter)