log.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 os
  25. import sys
  26. import threading
  27. try:
  28. from systemd import journal
  29. except ImportError:
  30. journal = None
  31. LOGGER_NAME = "radicale"
  32. LOGGER_FORMAT = "[%(processName)s/%(threadName)s] %(levelname)s: %(message)s"
  33. root_logger = logging.getLogger()
  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 ThreadStreamsHandler(logging.Handler):
  41. terminator = "\n"
  42. def __init__(self, fallback_stream, fallback_handler):
  43. super().__init__()
  44. self._streams = {}
  45. self.fallback_stream = fallback_stream
  46. self.fallback_handler = fallback_handler
  47. def setFormatter(self, form):
  48. super().setFormatter(form)
  49. self.fallback_handler.setFormatter(form)
  50. def emit(self, record):
  51. try:
  52. stream = self._streams.get(threading.get_ident())
  53. if stream is None:
  54. self.fallback_handler.emit(record)
  55. else:
  56. msg = self.format(record)
  57. stream.write(msg)
  58. stream.write(self.terminator)
  59. if hasattr(stream, "flush"):
  60. stream.flush()
  61. except Exception:
  62. self.handleError(record)
  63. @contextlib.contextmanager
  64. def register_stream(self, stream):
  65. if stream == self.fallback_stream:
  66. yield
  67. return
  68. key = threading.get_ident()
  69. self._streams[key] = stream
  70. try:
  71. yield
  72. finally:
  73. del self._streams[key]
  74. def get_default_handler():
  75. handler = logging.StreamHandler(sys.stderr)
  76. # Detect systemd journal
  77. with contextlib.suppress(ValueError, io.UnsupportedOperation):
  78. journal_dev, journal_ino = map(
  79. int, os.environ.get("JOURNAL_STREAM", "").split(":"))
  80. st = os.fstat(sys.stderr.fileno())
  81. if (journal and
  82. st.st_dev == journal_dev and st.st_ino == journal_ino):
  83. handler = journal.JournalHandler(SYSLOG_IDENTIFIER=LOGGER_NAME)
  84. return handler
  85. @contextlib.contextmanager
  86. def register_stream(stream):
  87. """Register global errors stream for the current thread."""
  88. yield
  89. def setup():
  90. """Set global logging up."""
  91. global register_stream, unregister_stream
  92. handler = ThreadStreamsHandler(sys.stderr, get_default_handler())
  93. logging.basicConfig(format=LOGGER_FORMAT, handlers=[handler])
  94. register_stream = handler.register_stream
  95. set_level(logging.DEBUG)
  96. def set_level(level):
  97. """Set logging level for global logger."""
  98. if isinstance(level, str):
  99. level = getattr(logging, level.upper())
  100. root_logger.setLevel(level)
  101. logger.setLevel(level)
  102. if level == logging.DEBUG:
  103. logger.removeFilter(removeTracebackFilter)
  104. else:
  105. logger.addFilter(removeTracebackFilter)