log.py 2.4 KB

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