1
0

logging_setup.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. from synapse.synapse_rust import reset_logging_config
  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: logging.LogRecord) -> None:
  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() -> None:
  29. """Configure the python logging appropriately for the tests.
  30. (Logs will end up in _trial_temp.)
  31. """
  32. root_logger = logging.getLogger()
  33. # We exclude `%(asctime)s` from this format because the Twisted logger adds its own
  34. # timestamp
  35. log_format = "%(name)s - %(lineno)d - " "%(levelname)s - %(request)s - %(message)s"
  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)
  43. # In order to not add noise by default (since we only log ERROR messages for trial
  44. # tests as configured above), we only enable this for developers for looking for
  45. # more INFO or DEBUG.
  46. if root_logger.isEnabledFor(logging.INFO):
  47. # Log when events are (maybe unexpectedly) filtered out of responses in tests. It's
  48. # just nice to be able to look at the CI log and figure out why an event isn't being
  49. # returned.
  50. logging.getLogger("synapse.visibility.filtered_event_debug").setLevel(
  51. logging.DEBUG
  52. )
  53. # Blow away the pyo3-log cache so that it reloads the configuration.
  54. reset_logging_config()