log.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 os
  22. import sys
  23. import logging
  24. import logging.config
  25. import signal
  26. def configure_from_file(filename, debug, logger):
  27. logging.config.fileConfig(filename)
  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 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_generator(logger, filename, debug):
  42. def handler(signum, frame):
  43. configure_from_file(logger, filename, debug)
  44. handler = handler_generator(logger, filename, debug)
  45. signal.signal(signal.SIGHUP, handler)
  46. else:
  47. # Default configuration, standard output
  48. if filename:
  49. logger.warning(
  50. "Logging configuration file '%s' not found, using stdout." %
  51. filename)
  52. handler = logging.StreamHandler(sys.stdout)
  53. handler.setFormatter(logging.Formatter("%(message)s"))
  54. logger.addHandler(handler)
  55. if debug:
  56. logger.setLevel(logging.DEBUG)
  57. return logger