From 1c093509ceb04ee8ce0eb6a408b76b0fda3ac87c Mon Sep 17 00:00:00 2001 From: Eric Eastwood Date: Thu, 2 Oct 2025 10:22:25 -0500 Subject: [PATCH] Switch task scheduler from raw logcontext manipulation (`set_current_context`) to utils (`PreserveLoggingContext`) (#18990) Prefer the utils over raw logcontext manipulation. Spawning from adding some logcontext debug logs in https://github.com/element-hq/synapse/pull/18966 and since we're not logging at the `set_current_context(...)` level (see reasoning there), this removes some usage of `set_current_context(...)`. --- changelog.d/18990.misc | 1 + synapse/util/task_scheduler.py | 7 ++----- 2 files changed, 3 insertions(+), 5 deletions(-) create mode 100644 changelog.d/18990.misc diff --git a/changelog.d/18990.misc b/changelog.d/18990.misc new file mode 100644 index 000000000..f7f8ac5ff --- /dev/null +++ b/changelog.d/18990.misc @@ -0,0 +1 @@ +Switch task scheduler from raw logcontext manipulation to using the dedicated logcontext utils. diff --git a/synapse/util/task_scheduler.py b/synapse/util/task_scheduler.py index 7443d4e09..8dd6f12fe 100644 --- a/synapse/util/task_scheduler.py +++ b/synapse/util/task_scheduler.py @@ -27,8 +27,8 @@ from twisted.python.failure import Failure from synapse.logging.context import ( ContextResourceUsage, LoggingContext, + PreserveLoggingContext, nested_logging_context, - set_current_context, ) from synapse.metrics import SERVER_NAME_LABEL, LaterGauge from synapse.metrics.background_process_metrics import ( @@ -422,14 +422,11 @@ class TaskScheduler: """ current_time = self._clock.time() - calling_context = set_current_context(task_log_context) - try: + with PreserveLoggingContext(task_log_context): usage = task_log_context.get_resource_usage() TaskScheduler._log_task_usage( "continuing", task, usage, current_time - start_time ) - finally: - set_current_context(calling_context) async def wrapper() -> None: with nested_logging_context(task.id) as log_context: