log.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011-2016 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. def start(name="radicale", filename=None, debug=False):
  34. """Start the logging according to the configuration."""
  35. logger = logging.getLogger(name)
  36. if filename and os.path.exists(filename):
  37. # Configuration taken from file
  38. configure_from_file(logger, filename, debug)
  39. # Reload config on SIGHUP (UNIX only)
  40. if hasattr(signal, "SIGHUP"):
  41. def handler(signum, frame):
  42. configure_from_file(logger, filename, debug)
  43. signal.signal(signal.SIGHUP, handler)
  44. else:
  45. # Default configuration, standard output
  46. if filename:
  47. logger.warning(
  48. "Logging configuration file '%s' not found, using stderr." %
  49. filename)
  50. handler = logging.StreamHandler(sys.stderr)
  51. handler.setFormatter(
  52. logging.Formatter("[%(thread)x] %(levelname)s: %(message)s"))
  53. logger.addHandler(handler)
  54. if debug:
  55. logger.setLevel(logging.DEBUG)
  56. return logger