logger.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ._base import Config
  16. from synapse.util.logcontext import LoggingContextFilter
  17. from twisted.python.log import PythonLoggingObserver
  18. import logging
  19. import logging.config
  20. class LoggingConfig(Config):
  21. def __init__(self, args):
  22. super(LoggingConfig, self).__init__(args)
  23. self.verbosity = int(args.verbose) if args.verbose else None
  24. self.log_config = self.abspath(args.log_config)
  25. self.log_file = self.abspath(args.log_file)
  26. @classmethod
  27. def add_arguments(cls, parser):
  28. super(LoggingConfig, cls).add_arguments(parser)
  29. logging_group = parser.add_argument_group("logging")
  30. logging_group.add_argument(
  31. '-v', '--verbose', dest="verbose", action='count',
  32. help="The verbosity level."
  33. )
  34. logging_group.add_argument(
  35. '-f', '--log-file', dest="log_file", default=None,
  36. help="File to log to."
  37. )
  38. logging_group.add_argument(
  39. '--log-config', dest="log_config", default=None,
  40. help="Python logging config file"
  41. )
  42. def setup_logging(self):
  43. log_format = (
  44. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s"
  45. " - %(message)s"
  46. )
  47. if self.log_config is None:
  48. level = logging.INFO
  49. if self.verbosity:
  50. level = logging.DEBUG
  51. # FIXME: we need a logging.WARN for a -q quiet option
  52. logger = logging.getLogger('')
  53. logger.setLevel(level)
  54. formatter = logging.Formatter(log_format)
  55. if self.log_file:
  56. handler = logging.FileHandler(self.log_file)
  57. else:
  58. handler = logging.StreamHandler()
  59. print handler
  60. handler.setFormatter(formatter)
  61. handler.addFilter(LoggingContextFilter(request=""))
  62. logger.addHandler(handler)
  63. logger.info("Test")
  64. else:
  65. logging.config.fileConfig(self.log_config)
  66. observer = PythonLoggingObserver()
  67. observer.start()