Skip to content

Commit a677d9b

Browse files
committed
Remove sentinel context from atexit daemonize logs
``` 2025-08-26 18:40:27,996 - my.synapse.linux.server - synapse.app.homeserver - 187 - WARNING - main - Starting daemon. 2025-08-26 18:40:27,996 - my.synapse.linux.server - synapse.app.homeserver - 181 - WARNING - atexit - Stopping daemon. ```
1 parent bf21b4a commit a677d9b

1 file changed

Lines changed: 26 additions & 3 deletions

File tree

synapse/util/daemonize.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
from synapse.logging.context import (
3333
SENTINEL_CONTEXT,
34+
LoggingContext,
3435
PreserveLoggingContext,
3536
)
3637

@@ -149,11 +150,33 @@ def sigterm(signum: int, frame: Optional[FrameType]) -> NoReturn:
149150

150151
signal.signal(signal.SIGTERM, sigterm)
151152

153+
# Create a logging context that we can use later as these `atexit` handlers will run
154+
# after the `with LoggingContext("main")` context manager finishes and we still want
155+
# some context here to know which server is logging.
156+
#
157+
# We're using `PreserveLoggingContext(SENTINEL_CONTEXT)` so our new `LoggingContext`
158+
# ends up with `LoggingContext.previous_context = SENTINEL_CONTEXT` so that when the
159+
# `LoggingContext` exits and restores the previous context, we don't leak some
160+
# context into the reactor that would be erroneously be picked up by something else
161+
# down the line.
162+
with PreserveLoggingContext(SENTINEL_CONTEXT):
163+
exit_logging_context = LoggingContext(
164+
"atexit",
165+
# TODO: In the future, we will want
166+
# `server_name=calling_context.server_name` so we know which server this log
167+
# pertains to, https://github.com/element-hq/synapse/pull/18868
168+
#
169+
# No parent_context as we don't want to attribute the metrics/traces to the
170+
# calling context. `atexit` is completely out-of-band from our application
171+
# so it doesn't make sense to associate it back.
172+
)
173+
152174
# Cleanup pid file at exit.
153175
def exit() -> None:
154-
logger.warning("Stopping daemon.")
155-
os.remove(pid_file)
156-
sys.exit(0)
176+
with PreserveLoggingContext(exit_logging_context):
177+
logger.warning("Stopping daemon.")
178+
os.remove(pid_file)
179+
sys.exit(0)
157180

158181
atexit.register(exit)
159182

0 commit comments

Comments
 (0)