|
31 | 31 |
|
32 | 32 | from synapse.logging.context import ( |
33 | 33 | SENTINEL_CONTEXT, |
| 34 | + LoggingContext, |
34 | 35 | PreserveLoggingContext, |
35 | 36 | ) |
36 | 37 |
|
@@ -149,11 +150,33 @@ def sigterm(signum: int, frame: Optional[FrameType]) -> NoReturn: |
149 | 150 |
|
150 | 151 | signal.signal(signal.SIGTERM, sigterm) |
151 | 152 |
|
| 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 | + |
152 | 174 | # Cleanup pid file at exit. |
153 | 175 | 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) |
157 | 180 |
|
158 | 181 | atexit.register(exit) |
159 | 182 |
|
|
0 commit comments