test_terse_json.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. import logging
  17. from io import BytesIO, StringIO
  18. from unittest.mock import Mock, patch
  19. from twisted.web.server import Request
  20. from synapse.http.site import SynapseRequest
  21. from synapse.logging._terse_json import JsonFormatter, TerseJsonFormatter
  22. from synapse.logging.context import LoggingContext, LoggingContextFilter
  23. from tests.logging import LoggerCleanupMixin
  24. from tests.server import FakeChannel
  25. from tests.unittest import TestCase
  26. class TerseJsonTestCase(LoggerCleanupMixin, TestCase):
  27. def setUp(self):
  28. self.output = StringIO()
  29. def get_log_line(self):
  30. # One log message, with a single trailing newline.
  31. data = self.output.getvalue()
  32. logs = data.splitlines()
  33. self.assertEqual(len(logs), 1)
  34. self.assertEqual(data.count("\n"), 1)
  35. return json.loads(logs[0])
  36. def test_terse_json_output(self):
  37. """
  38. The Terse JSON formatter converts log messages to JSON.
  39. """
  40. handler = logging.StreamHandler(self.output)
  41. handler.setFormatter(TerseJsonFormatter())
  42. logger = self.get_logger(handler)
  43. logger.info("Hello there, %s!", "wally")
  44. log = self.get_log_line()
  45. # The terse logger should give us these keys.
  46. expected_log_keys = [
  47. "log",
  48. "time",
  49. "level",
  50. "namespace",
  51. ]
  52. self.assertCountEqual(log.keys(), expected_log_keys)
  53. self.assertEqual(log["log"], "Hello there, wally!")
  54. def test_extra_data(self):
  55. """
  56. Additional information can be included in the structured logging.
  57. """
  58. handler = logging.StreamHandler(self.output)
  59. handler.setFormatter(TerseJsonFormatter())
  60. logger = self.get_logger(handler)
  61. logger.info(
  62. "Hello there, %s!", "wally", extra={"foo": "bar", "int": 3, "bool": True}
  63. )
  64. log = self.get_log_line()
  65. # The terse logger should give us these keys.
  66. expected_log_keys = [
  67. "log",
  68. "time",
  69. "level",
  70. "namespace",
  71. # The additional keys given via extra.
  72. "foo",
  73. "int",
  74. "bool",
  75. ]
  76. self.assertCountEqual(log.keys(), expected_log_keys)
  77. # Check the values of the extra fields.
  78. self.assertEqual(log["foo"], "bar")
  79. self.assertEqual(log["int"], 3)
  80. self.assertIs(log["bool"], True)
  81. def test_json_output(self):
  82. """
  83. The Terse JSON formatter converts log messages to JSON.
  84. """
  85. handler = logging.StreamHandler(self.output)
  86. handler.setFormatter(JsonFormatter())
  87. logger = self.get_logger(handler)
  88. logger.info("Hello there, %s!", "wally")
  89. log = self.get_log_line()
  90. # The terse logger should give us these keys.
  91. expected_log_keys = [
  92. "log",
  93. "level",
  94. "namespace",
  95. ]
  96. self.assertCountEqual(log.keys(), expected_log_keys)
  97. self.assertEqual(log["log"], "Hello there, wally!")
  98. def test_with_context(self):
  99. """
  100. The logging context should be added to the JSON response.
  101. """
  102. handler = logging.StreamHandler(self.output)
  103. handler.setFormatter(JsonFormatter())
  104. handler.addFilter(LoggingContextFilter())
  105. logger = self.get_logger(handler)
  106. with LoggingContext("name"):
  107. logger.info("Hello there, %s!", "wally")
  108. log = self.get_log_line()
  109. # The terse logger should give us these keys.
  110. expected_log_keys = [
  111. "log",
  112. "level",
  113. "namespace",
  114. "request",
  115. ]
  116. self.assertCountEqual(log.keys(), expected_log_keys)
  117. self.assertEqual(log["log"], "Hello there, wally!")
  118. self.assertEqual(log["request"], "name")
  119. def test_with_request_context(self):
  120. """
  121. Information from the logging context request should be added to the JSON response.
  122. """
  123. handler = logging.StreamHandler(self.output)
  124. handler.setFormatter(JsonFormatter())
  125. handler.addFilter(LoggingContextFilter())
  126. logger = self.get_logger(handler)
  127. # A full request isn't needed here.
  128. site = Mock(spec=["site_tag", "server_version_string", "getResourceFor"])
  129. site.site_tag = "test-site"
  130. site.server_version_string = "Server v1"
  131. request = SynapseRequest(FakeChannel(site, None))
  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"], "")