Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 1619802

Browse files
authored
Various clean-ups to the logging context code (#8935)
1 parent 895e043 commit 1619802

File tree

11 files changed

+20
-39
lines changed

11 files changed

+20
-39
lines changed

changelog.d/8916.misc

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Improve structured logging tests.
1+
Various clean-ups to the structured logging and logging context code.

changelog.d/8935.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Various clean-ups to the structured logging and logging context code.

synapse/config/logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ def _setup_stdlib_logging(config, log_config_path, logBeginner: LogBeginner) ->
206206
# filter options, but care must when using e.g. MemoryHandler to buffer
207207
# writes.
208208

209-
log_context_filter = LoggingContextFilter(request="")
209+
log_context_filter = LoggingContextFilter()
210210
log_metadata_filter = MetadataFilter({"server_name": config.server_name})
211211
old_factory = logging.getLogRecordFactory()
212212

synapse/http/site.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,7 @@ def render(self, resrc):
128128

129129
# create a LogContext for this request
130130
request_id = self.get_request_id()
131-
logcontext = self.logcontext = LoggingContext(request_id)
132-
logcontext.request = request_id
131+
self.logcontext = LoggingContext(request_id, request=request_id)
133132

134133
# override the Server header which is set by twisted
135134
self.setHeader("Server", self.site.server_version_string)

synapse/logging/context.py

+5-19
Original file line numberDiff line numberDiff line change
@@ -203,10 +203,6 @@ def __str__(self):
203203
def copy_to(self, record):
204204
pass
205205

206-
def copy_to_twisted_log_entry(self, record):
207-
record["request"] = None
208-
record["scope"] = None
209-
210206
def start(self, rusage: "Optional[resource._RUsage]"):
211207
pass
212208

@@ -372,13 +368,6 @@ def copy_to(self, record) -> None:
372368
# we also track the current scope:
373369
record.scope = self.scope
374370

375-
def copy_to_twisted_log_entry(self, record) -> None:
376-
"""
377-
Copy logging fields from this context to a Twisted log record.
378-
"""
379-
record["request"] = self.request
380-
record["scope"] = self.scope
381-
382371
def start(self, rusage: "Optional[resource._RUsage]") -> None:
383372
"""
384373
Record that this logcontext is currently running.
@@ -542,28 +531,25 @@ def record_event_fetch(self, event_count: int) -> None:
542531
class LoggingContextFilter(logging.Filter):
543532
"""Logging filter that adds values from the current logging context to each
544533
record.
545-
Args:
546-
**defaults: Default values to avoid formatters complaining about
547-
missing fields
548534
"""
549535

550-
def __init__(self, **defaults) -> None:
551-
self.defaults = defaults
536+
def __init__(self, request: str = ""):
537+
self._default_request = request
552538

553539
def filter(self, record) -> Literal[True]:
554540
"""Add each fields from the logging contexts to the record.
555541
Returns:
556542
True to include the record in the log output.
557543
"""
558544
context = current_context()
559-
for key, value in self.defaults.items():
560-
setattr(record, key, value)
545+
record.request = self._default_request
561546

562547
# context should never be None, but if it somehow ends up being, then
563548
# we end up in a death spiral of infinite loops, so let's check, for
564549
# robustness' sake.
565550
if context is not None:
566-
context.copy_to(record)
551+
# Logging is interested in the request.
552+
record.request = context.request
567553

568554
return True
569555

synapse/metrics/background_process_metrics.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,7 @@ async def run():
199199
_background_process_start_count.labels(desc).inc()
200200
_background_process_in_flight_count.labels(desc).inc()
201201

202-
with BackgroundProcessLoggingContext(desc) as context:
203-
context.request = "%s-%i" % (desc, count)
202+
with BackgroundProcessLoggingContext(desc, "%s-%i" % (desc, count)) as context:
204203
try:
205204
ctx = noop_context_manager()
206205
if bg_start_span:
@@ -244,8 +243,8 @@ class BackgroundProcessLoggingContext(LoggingContext):
244243

245244
__slots__ = ["_proc"]
246245

247-
def __init__(self, name: str):
248-
super().__init__(name)
246+
def __init__(self, name: str, request: Optional[str] = None):
247+
super().__init__(name, request=request)
249248

250249
self._proc = _BackgroundProcess(name, self)
251250

synapse/replication/tcp/protocol.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,7 @@ def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
172172
# a logcontext which we use for processing incoming commands. We declare it as a
173173
# background process so that the CPU stats get reported to prometheus.
174174
ctx_name = "replication-conn-%s" % self.conn_id
175-
self._logging_context = BackgroundProcessLoggingContext(ctx_name)
176-
self._logging_context.request = ctx_name
175+
self._logging_context = BackgroundProcessLoggingContext(ctx_name, ctx_name)
177176

178177
def connectionMade(self):
179178
logger.info("[%s] Connection established", self.id())

tests/handlers/test_federation.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def test_rejected_message_event_state(self):
126126
room_version,
127127
)
128128

129-
with LoggingContext(request="send_rejected"):
129+
with LoggingContext("send_rejected"):
130130
d = run_in_background(self.handler.on_receive_pdu, OTHER_SERVER, ev)
131131
self.get_success(d)
132132

@@ -178,7 +178,7 @@ def test_rejected_state_event_state(self):
178178
room_version,
179179
)
180180

181-
with LoggingContext(request="send_rejected"):
181+
with LoggingContext("send_rejected"):
182182
d = run_in_background(self.handler.on_receive_pdu, OTHER_SERVER, ev)
183183
self.get_success(d)
184184

@@ -198,7 +198,7 @@ def _build_and_send_join_event(self, other_server, other_user, room_id):
198198
# the auth code requires that a signature exists, but doesn't check that
199199
# signature... go figure.
200200
join_event.signatures[other_server] = {"x": "y"}
201-
with LoggingContext(request="send_join"):
201+
with LoggingContext("send_join"):
202202
d = run_in_background(
203203
self.handler.on_send_join_request, other_server, join_event
204204
)

tests/logging/test_terse_json.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,10 @@ def test_with_context(self):
117117
"""
118118
handler = logging.StreamHandler(self.output)
119119
handler.setFormatter(JsonFormatter())
120-
handler.addFilter(LoggingContextFilter(request=""))
120+
handler.addFilter(LoggingContextFilter())
121121
logger = self.get_logger(handler)
122122

123-
with LoggingContext() as context_one:
124-
context_one.request = "test"
123+
with LoggingContext(request="test"):
125124
logger.info("Hello there, %s!", "wally")
126125

127126
log = self.get_log_line()
@@ -132,9 +131,7 @@ def test_with_context(self):
132131
"level",
133132
"namespace",
134133
"request",
135-
"scope",
136134
]
137135
self.assertCountEqual(log.keys(), expected_log_keys)
138136
self.assertEqual(log["log"], "Hello there, wally!")
139137
self.assertEqual(log["request"], "test")
140-
self.assertIsNone(log["scope"])

tests/test_federation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ async def post_json(destination, path, data, headers=None, timeout=0):
134134
}
135135
)
136136

137-
with LoggingContext(request="lying_event"):
137+
with LoggingContext():
138138
failure = self.get_failure(
139139
self.handler.on_receive_pdu(
140140
"test.serv", lying_event, sent_to_us_directly=True

tests/test_utils/logging_setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def setup_logging():
4848
handler = ToTwistedHandler()
4949
formatter = logging.Formatter(log_format)
5050
handler.setFormatter(formatter)
51-
handler.addFilter(LoggingContextFilter(request=""))
51+
handler.addFilter(LoggingContextFilter())
5252
root_logger.addHandler(handler)
5353

5454
log_level = os.environ.get("SYNAPSE_TEST_LOG_LEVEL", "ERROR")

0 commit comments

Comments
 (0)