From fd61bcdcab80970ea689d0c013a394a246b58701 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Wed, 22 Nov 2023 11:46:55 +0100 Subject: [PATCH] monitor: introduce `Context.with_origin()` The existing JSONSeqMonitor was saving/restoring the "origin" when generating a new log-entry. This allows logging from different origins (e.g. "org.osbuild.main") in a kind of "out-of-band" fashion. But this save/restore feels slightly inelegant because JSONSeqMonitor feels like the wrong layer to deal with this. This is why a new `with_origin()` helper is introduced that will either reuse the existing context or create a new one with the requested origin. --- osbuild/monitor.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/osbuild/monitor.py b/osbuild/monitor.py index 05d16efa..dca0ae93 100644 --- a/osbuild/monitor.py +++ b/osbuild/monitor.py @@ -9,6 +9,7 @@ are called on the monitor object at certain events. Consult the """ import abc +import copy import datetime import hashlib import json @@ -52,6 +53,18 @@ class Context: if name != "_id": super().__setattr__("_id", None) + def with_origin(self, origin: Optional[str]) -> "Context": + """ + Return a Context with the given origin but otherwise identical. + + Note that if the origin is empty or same it will return self. + """ + if origin is None or origin == self._origin: + return self + ctx = copy.copy(self) + ctx.set_origin(origin) + return ctx + @property def origin(self): return self._origin @@ -322,13 +335,8 @@ class JSONSeqMonitor(BaseMonitor): self._context.set_stage(module) def log(self, message, origin: Optional[str] = None): - oo = self._context.origin - if origin is not None: - self._context.set_origin(origin) - entry = log_entry(message=message, context=self._context, progress=self._progress) + entry = log_entry(message, self._context.with_origin(origin), self._progress) self._jsonseq(entry) - # restore old origin - self._context.set_origin(oo) def _jsonseq(self, entry): # follow rfc7464 (application/json-seq)