log.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 logging
  22. import logging.config
  23. import signal
  24. import sys
  25. def configure_from_file(logger, filename, debug):
  26. logging.config.fileConfig(filename, disable_existing_loggers=False)
  27. if debug:
  28. logger.setLevel(logging.DEBUG)
  29. for handler in logger.handlers:
  30. handler.setLevel(logging.DEBUG)
  31. return logger
  32. class RemoveTracebackFilter(logging.Filter):
  33. def filter(self, record):
  34. record.exc_info = None
  35. return True
  36. def start(name="radicale", filename=None, debug=False):
  37. """Start the logging according to the configuration."""
  38. logger = logging.getLogger(name)
  39. if debug:
  40. logger.setLevel(logging.DEBUG)
  41. else:
  42. logger.addFilter(RemoveTracebackFilter())
  43. if filename:
  44. # Configuration taken from file
  45. try:
  46. configure_from_file(logger, filename, debug)
  47. except Exception as e:
  48. raise RuntimeError("Failed to load logging configuration file %r: "
  49. "%s" % (filename, e)) from e
  50. # Reload config on SIGHUP (UNIX only)
  51. if hasattr(signal, "SIGHUP"):
  52. def handler(signum, frame):
  53. try:
  54. configure_from_file(logger, filename, debug)
  55. except Exception as e:
  56. logger.error("Failed to reload logging configuration file "
  57. "%r: %s", filename, e, exc_info=True)
  58. signal.signal(signal.SIGHUP, handler)
  59. else:
  60. # Default configuration, standard output
  61. handler = logging.StreamHandler(sys.stderr)
  62. handler.setFormatter(
  63. logging.Formatter("[%(thread)x] %(levelname)s: %(message)s"))
  64. logger.addHandler(handler)
  65. return logger