log.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2017 Guillaume Ayoub
  3. #
  4. # This library is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. Radicale logging module.
  18. Manage logging from a configuration file. For more information, see:
  19. http://docs.python.org/library/logging.config.html
  20. """
  21. import contextlib
  22. import io
  23. import logging
  24. import multiprocessing
  25. import os
  26. import sys
  27. import threading
  28. try:
  29. from systemd import journal
  30. except ImportError:
  31. journal = None
  32. LOGGER_NAME = "radicale"
  33. LOGGER_FORMAT = "[%(ident)s] %(levelname)s: %(message)s"
  34. logger = logging.getLogger(LOGGER_NAME)
  35. class RemoveTracebackFilter(logging.Filter):
  36. def filter(self, record):
  37. record.exc_info = None
  38. return True
  39. removeTracebackFilter = RemoveTracebackFilter()
  40. class IdentLogRecordFactory:
  41. """LogRecordFactory that adds ``ident`` attribute."""
  42. def __init__(self, upstream_factory):
  43. self.upstream_factory = upstream_factory
  44. self.main_pid = os.getpid()
  45. def __call__(self, *args, **kwargs):
  46. record = self.upstream_factory(*args, **kwargs)
  47. pid = os.getpid()
  48. ident = "%x" % self.main_pid
  49. if pid != self.main_pid:
  50. ident += "%+x" % (pid - self.main_pid)
  51. main_thread = threading.main_thread()
  52. current_thread = threading.current_thread()
  53. if current_thread.name and main_thread != current_thread:
  54. ident += "/%s" % current_thread.name
  55. record.ident = ident
  56. return record
  57. class ThreadStreamsHandler(logging.Handler):
  58. terminator = "\n"
  59. def __init__(self, fallback_stream, fallback_handler):
  60. super().__init__()
  61. self._streams = {}
  62. self.fallback_stream = fallback_stream
  63. self.fallback_handler = fallback_handler
  64. def createLock(self):
  65. self.lock = multiprocessing.Lock()
  66. def setFormatter(self, form):
  67. super().setFormatter(form)
  68. self.fallback_handler.setFormatter(form)
  69. def emit(self, record):
  70. try:
  71. stream = self._streams.get(threading.get_ident())
  72. if stream is None:
  73. self.fallback_handler.emit(record)
  74. else:
  75. msg = self.format(record)
  76. stream.write(msg)
  77. stream.write(self.terminator)
  78. if hasattr(stream, "flush"):
  79. stream.flush()
  80. except Exception:
  81. self.handleError(record)
  82. @contextlib.contextmanager
  83. def register_stream(self, stream):
  84. if stream == self.fallback_stream:
  85. yield
  86. return
  87. key = threading.get_ident()
  88. self._streams[key] = stream
  89. try:
  90. yield
  91. finally:
  92. del self._streams[key]
  93. def get_default_handler():
  94. handler = logging.StreamHandler(sys.stderr)
  95. # Detect systemd journal
  96. with contextlib.suppress(ValueError, io.UnsupportedOperation):
  97. journal_dev, journal_ino = map(
  98. int, os.environ.get("JOURNAL_STREAM", "").split(":"))
  99. st = os.fstat(sys.stderr.fileno())
  100. if (journal and
  101. st.st_dev == journal_dev and st.st_ino == journal_ino):
  102. handler = journal.JournalHandler(SYSLOG_IDENTIFIER=LOGGER_NAME)
  103. return handler
  104. @contextlib.contextmanager
  105. def register_stream(stream):
  106. """Register global errors stream for the current thread."""
  107. yield
  108. def setup():
  109. """Set global logging up."""
  110. global register_stream, unregister_stream
  111. handler = ThreadStreamsHandler(sys.stderr, get_default_handler())
  112. logging.basicConfig(format=LOGGER_FORMAT, handlers=[handler])
  113. register_stream = handler.register_stream
  114. log_record_factory = IdentLogRecordFactory(logging.getLogRecordFactory())
  115. logging.setLogRecordFactory(log_record_factory)
  116. set_level(logging.DEBUG)
  117. def set_level(level):
  118. """Set logging level for global logger."""
  119. if isinstance(level, str):
  120. level = getattr(logging, level.upper())
  121. logger.setLevel(level)
  122. if level == logging.DEBUG:
  123. logger.removeFilter(removeTracebackFilter)
  124. else:
  125. logger.addFilter(removeTracebackFilter)