logging_setup.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2019 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import os
  16. import twisted.logger
  17. from synapse.logging.context import LoggingContextFilter
  18. class ToTwistedHandler(logging.Handler):
  19. """logging handler which sends the logs to the twisted log"""
  20. tx_log = twisted.logger.Logger()
  21. def emit(self, record):
  22. log_entry = self.format(record)
  23. log_level = record.levelname.lower().replace("warning", "warn")
  24. self.tx_log.emit(
  25. twisted.logger.LogLevel.levelWithName(log_level), "{entry}", entry=log_entry
  26. )
  27. def setup_logging():
  28. """Configure the python logging appropriately for the tests.
  29. (Logs will end up in _trial_temp.)
  30. """
  31. root_logger = logging.getLogger()
  32. log_format = (
  33. "%(asctime)s - %(name)s - %(lineno)d - "
  34. "%(levelname)s - %(request)s - %(message)s"
  35. )
  36. handler = ToTwistedHandler()
  37. formatter = logging.Formatter(log_format)
  38. handler.setFormatter(formatter)
  39. handler.addFilter(LoggingContextFilter())
  40. root_logger.addHandler(handler)
  41. log_level = os.environ.get("SYNAPSE_TEST_LOG_LEVEL", "ERROR")
  42. root_logger.setLevel(log_level)