From 1efccf34b12ceaf3565bd70b8c3b3465e65d4a18 Mon Sep 17 00:00:00 2001 From: Eelco Dolstra 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, 14 insertions(+), 2 deletions(-) diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index fcbc61d5e..c3ccfba42 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 #include @@ -192,11 +193,22 @@ struct JSONLogger : Logger { unreachable(); } + struct State + { + }; + + Sync _state; + void write(const nlohmann::json & json) { - writeLine(fd, + auto line = (includeNixPrefix ? "@nix " : "") + - json.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)); + 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