1
0

logging_setup.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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),
  27. log_entry.replace("{", r"(").replace("}", r")"),
  28. )
  29. def setup_logging():
  30. """Configure the python logging appropriately for the tests.
  31. (Logs will end up in _trial_temp.)
  32. """
  33. root_logger = logging.getLogger()
  34. log_format = (
  35. "%(asctime)s - %(name)s - %(lineno)d - "
  36. "%(levelname)s - %(request)s - %(message)s"
  37. )
  38. handler = ToTwistedHandler()
  39. formatter = logging.Formatter(log_format)
  40. handler.setFormatter(formatter)
  41. handler.addFilter(LoggingContextFilter(request=""))
  42. root_logger.addHandler(handler)
  43. log_level = os.environ.get("SYNAPSE_TEST_LOG_LEVEL", "ERROR")
  44. root_logger.setLevel(log_level)