test_terse_json.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. site.reactor = Mock()
  131. site.experimental_cors_msc3886 = False
  132. request = SynapseRequest(FakeChannel(site, None), site)
  133. # Call requestReceived to finish instantiating the object.
  134. request.content = BytesIO()
  135. # Partially skip some of the internal processing of SynapseRequest.
  136. request._started_processing = Mock()
  137. request.request_metrics = Mock(spec=["name"])
  138. with patch.object(Request, "render"):
  139. request.requestReceived(b"POST", b"/_matrix/client/versions", b"1.1")
  140. # Also set the requester to ensure the processing works.
  141. request.requester = "@foo:test"
  142. with LoggingContext(
  143. request.get_request_id(), parent_context=request.logcontext
  144. ):
  145. logger.info("Hello there, %s!", "wally")
  146. log = self.get_log_line()
  147. # The terse logger includes additional request information, if possible.
  148. expected_log_keys = [
  149. "log",
  150. "level",
  151. "namespace",
  152. "request",
  153. "ip_address",
  154. "site_tag",
  155. "requester",
  156. "authenticated_entity",
  157. "method",
  158. "url",
  159. "protocol",
  160. "user_agent",
  161. ]
  162. self.assertCountEqual(log.keys(), expected_log_keys)
  163. self.assertEqual(log["log"], "Hello there, wally!")
  164. self.assertTrue(log["request"].startswith("POST-"))
  165. self.assertEqual(log["ip_address"], "127.0.0.1")
  166. self.assertEqual(log["site_tag"], "test-site")
  167. self.assertEqual(log["requester"], "@foo:test")
  168. self.assertEqual(log["authenticated_entity"], "@foo:test")
  169. self.assertEqual(log["method"], "POST")
  170. self.assertEqual(log["url"], "/_matrix/client/versions")
  171. self.assertEqual(log["protocol"], "1.1")
  172. self.assertEqual(log["user_agent"], "")
  173. def test_with_exception(self):
  174. """
  175. The logging exception type & value should be added to the JSON response.
  176. """
  177. handler = logging.StreamHandler(self.output)
  178. handler.setFormatter(JsonFormatter())
  179. logger = self.get_logger(handler)
  180. try:
  181. raise ValueError("That's wrong, you wally!")
  182. except ValueError:
  183. logger.exception("Hello there, %s!", "wally")
  184. log = self.get_log_line()
  185. # The terse logger should give us these keys.
  186. expected_log_keys = [
  187. "log",
  188. "level",
  189. "namespace",
  190. "exc_type",
  191. "exc_value",
  192. ]
  193. self.assertCountEqual(log.keys(), expected_log_keys)
  194. self.assertEqual(log["log"], "Hello there, wally!")
  195. self.assertEqual(log["exc_type"], "ValueError")
  196. self.assertEqual(log["exc_value"], "That's wrong, you wally!")