1
0

test_terse_json.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 json
  15. import logging
  16. from io import BytesIO, StringIO
  17. from unittest.mock import Mock, patch
  18. from twisted.web.server import Request
  19. from synapse.http.site import SynapseRequest
  20. from synapse.logging._terse_json import JsonFormatter, TerseJsonFormatter
  21. from synapse.logging.context import LoggingContext, LoggingContextFilter
  22. from tests.logging import LoggerCleanupMixin
  23. from tests.server import FakeChannel
  24. from tests.unittest import TestCase
  25. class TerseJsonTestCase(LoggerCleanupMixin, TestCase):
  26. def setUp(self):
  27. self.output = StringIO()
  28. def get_log_line(self):
  29. # One log message, with a single trailing newline.
  30. data = self.output.getvalue()
  31. logs = data.splitlines()
  32. self.assertEqual(len(logs), 1)
  33. self.assertEqual(data.count("\n"), 1)
  34. return json.loads(logs[0])
  35. def test_terse_json_output(self):
  36. """
  37. The Terse JSON formatter converts log messages to JSON.
  38. """
  39. handler = logging.StreamHandler(self.output)
  40. handler.setFormatter(TerseJsonFormatter())
  41. logger = self.get_logger(handler)
  42. logger.info("Hello there, %s!", "wally")
  43. log = self.get_log_line()
  44. # The terse logger should give us these keys.
  45. expected_log_keys = [
  46. "log",
  47. "time",
  48. "level",
  49. "namespace",
  50. ]
  51. self.assertCountEqual(log.keys(), expected_log_keys)
  52. self.assertEqual(log["log"], "Hello there, wally!")
  53. def test_extra_data(self):
  54. """
  55. Additional information can be included in the structured logging.
  56. """
  57. handler = logging.StreamHandler(self.output)
  58. handler.setFormatter(TerseJsonFormatter())
  59. logger = self.get_logger(handler)
  60. logger.info(
  61. "Hello there, %s!", "wally", extra={"foo": "bar", "int": 3, "bool": True}
  62. )
  63. log = self.get_log_line()
  64. # The terse logger should give us these keys.
  65. expected_log_keys = [
  66. "log",
  67. "time",
  68. "level",
  69. "namespace",
  70. # The additional keys given via extra.
  71. "foo",
  72. "int",
  73. "bool",
  74. ]
  75. self.assertCountEqual(log.keys(), expected_log_keys)
  76. # Check the values of the extra fields.
  77. self.assertEqual(log["foo"], "bar")
  78. self.assertEqual(log["int"], 3)
  79. self.assertIs(log["bool"], True)
  80. def test_json_output(self):
  81. """
  82. The Terse JSON formatter converts log messages to JSON.
  83. """
  84. handler = logging.StreamHandler(self.output)
  85. handler.setFormatter(JsonFormatter())
  86. logger = self.get_logger(handler)
  87. logger.info("Hello there, %s!", "wally")
  88. log = self.get_log_line()
  89. # The terse logger should give us these keys.
  90. expected_log_keys = [
  91. "log",
  92. "level",
  93. "namespace",
  94. ]
  95. self.assertCountEqual(log.keys(), expected_log_keys)
  96. self.assertEqual(log["log"], "Hello there, wally!")
  97. def test_with_context(self):
  98. """
  99. The logging context should be added to the JSON response.
  100. """
  101. handler = logging.StreamHandler(self.output)
  102. handler.setFormatter(JsonFormatter())
  103. handler.addFilter(LoggingContextFilter())
  104. logger = self.get_logger(handler)
  105. with LoggingContext("name"):
  106. logger.info("Hello there, %s!", "wally")
  107. log = self.get_log_line()
  108. # The terse logger should give us these keys.
  109. expected_log_keys = [
  110. "log",
  111. "level",
  112. "namespace",
  113. "request",
  114. ]
  115. self.assertCountEqual(log.keys(), expected_log_keys)
  116. self.assertEqual(log["log"], "Hello there, wally!")
  117. self.assertEqual(log["request"], "name")
  118. def test_with_request_context(self):
  119. """
  120. Information from the logging context request should be added to the JSON response.
  121. """
  122. handler = logging.StreamHandler(self.output)
  123. handler.setFormatter(JsonFormatter())
  124. handler.addFilter(LoggingContextFilter())
  125. logger = self.get_logger(handler)
  126. # A full request isn't needed here.
  127. site = Mock(spec=["site_tag", "server_version_string", "getResourceFor"])
  128. site.site_tag = "test-site"
  129. site.server_version_string = "Server v1"
  130. request = SynapseRequest(FakeChannel(site, None))
  131. # Call requestReceived to finish instantiating the object.
  132. request.content = BytesIO()
  133. # Partially skip some of the internal processing of SynapseRequest.
  134. request._started_processing = Mock()
  135. request.request_metrics = Mock(spec=["name"])
  136. with patch.object(Request, "render"):
  137. request.requestReceived(b"POST", b"/_matrix/client/versions", b"1.1")
  138. # Also set the requester to ensure the processing works.
  139. request.requester = "@foo:test"
  140. with LoggingContext(
  141. request.get_request_id(), parent_context=request.logcontext
  142. ):
  143. logger.info("Hello there, %s!", "wally")
  144. log = self.get_log_line()
  145. # The terse logger includes additional request information, if possible.
  146. expected_log_keys = [
  147. "log",
  148. "level",
  149. "namespace",
  150. "request",
  151. "ip_address",
  152. "site_tag",
  153. "requester",
  154. "authenticated_entity",
  155. "method",
  156. "url",
  157. "protocol",
  158. "user_agent",
  159. ]
  160. self.assertCountEqual(log.keys(), expected_log_keys)
  161. self.assertEqual(log["log"], "Hello there, wally!")
  162. self.assertTrue(log["request"].startswith("POST-"))
  163. self.assertEqual(log["ip_address"], "127.0.0.1")
  164. self.assertEqual(log["site_tag"], "test-site")
  165. self.assertEqual(log["requester"], "@foo:test")
  166. self.assertEqual(log["authenticated_entity"], "@foo:test")
  167. self.assertEqual(log["method"], "POST")
  168. self.assertEqual(log["url"], "/_matrix/client/versions")
  169. self.assertEqual(log["protocol"], "1.1")
  170. self.assertEqual(log["user_agent"], "")