1
0

logging_setup.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector 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. import logging
  16. import os
  17. import twisted.logger
  18. from synapse.logging.context import LoggingContextFilter
  19. class ToTwistedHandler(logging.Handler):
  20. """logging handler which sends the logs to the twisted log"""
  21. tx_log = twisted.logger.Logger()
  22. def emit(self, record):
  23. log_entry = self.format(record)
  24. log_level = record.levelname.lower().replace("warning", "warn")
  25. self.tx_log.emit(
  26. twisted.logger.LogLevel.levelWithName(log_level), "{entry}", entry=log_entry
  27. )
  28. def setup_logging():
  29. """Configure the python logging appropriately for the tests.
  30. (Logs will end up in _trial_temp.)
  31. """
  32. root_logger = logging.getLogger()
  33. log_format = (
  34. "%(asctime)s - %(name)s - %(lineno)d - "
  35. "%(levelname)s - %(request)s - %(message)s"
  36. )
  37. handler = ToTwistedHandler()
  38. formatter = logging.Formatter(log_format)
  39. handler.setFormatter(formatter)
  40. handler.addFilter(LoggingContextFilter())
  41. root_logger.addHandler(handler)
  42. log_level = os.environ.get("SYNAPSE_TEST_LOG_LEVEL", "ERROR")
  43. root_logger.setLevel(log_level)