1
0

test_terse_json.py 7.6 KB

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