From d0227f8d0245d6ec0c11d7e955f7681d8552ef63 Mon Sep 17 00:00:00 2001 From: Eelco Dolstra <edolstra@gmail.com> Date: Thu, 13 Mar 2025 13:58:35 +0100 Subject: [PATCH] JSONLogger: Acquire a lock to prevent log messages from clobbering each other --- src/libutil/logging.cc | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index 406452738..1b0b2d0d9 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -6,6 +6,7 @@ #include "config-global.hh" #include "source-path.hh" #include "position.hh" +#include "sync.hh" #include <atomic> #include <sstream> @@ -201,9 +202,22 @@ struct JSONLogger : Logger { unreachable(); } + struct State + { + }; + + Sync<State> _state; + void write(const nlohmann::json & json) { - writeLine(fd, "@nix " + json.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)); + auto line = + "@nix " + + json.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); + + /* Acquire a lock to prevent log messages from clobbering each + other. */ + auto state(_state.lock()); + writeLine(fd, line); } void log(Verbosity lvl, std::string_view s) override