test_terse_json.py 7.9 KB

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