diff options
author | eldritch horrors <pennae@lix.systems> | 2024-07-14 23:50:16 +0200 |
---|---|---|
committer | eldritch horrors <pennae@lix.systems> | 2024-07-20 12:33:49 +0000 |
commit | 0109368c3faf5516aeddde45e8dc3c33e7163838 (patch) | |
tree | f497a0354d3472be4ab7e32c111a6a57cf32aa84 /src/libutil/logging.cc | |
parent | d8c09b583644105c25e3023e98ffceb75333af2e (diff) |
libutil: make basic loggers thread-safe
SimpleLogger is not fully thread-safe, and all loggers that wrap it are
also not safe accordingly. this does not affect much, but in rare cases
it can cause interleaving of messages on stderr when used with the json
or raw log formats. the fix applied here is a bit of a hack, but fixing
this properly requires rearchitecting the logger infrastructure. nested
loggers are not the most natural abstraction here, and it is biting us.
Change-Id: Ifbf34fe1e85c60e73b59faee50e7411c7b5e7c12
Diffstat (limited to 'src/libutil/logging.cc')
-rw-r--r-- | src/libutil/logging.cc | 13 |
1 files changed, 11 insertions, 2 deletions
diff --git a/src/libutil/logging.cc b/src/libutil/logging.cc index fecbc89ac..d674c9651 100644 --- a/src/libutil/logging.cc +++ b/src/libutil/logging.cc @@ -77,7 +77,7 @@ public: prefix = std::string("<") + c + ">"; } - writeToStderr(prefix + filterANSIEscapes(s, !tty) + "\n"); + writeLogsToStderr(prefix + filterANSIEscapes(s, !tty) + "\n"); } void logEI(const ErrorInfo & ei) override @@ -117,8 +117,17 @@ Verbosity verbosityFromIntClamped(int val) return static_cast<Verbosity>(clamped); } -void writeToStderr(std::string_view s) +void writeLogsToStderr(std::string_view s) { + static std::mutex lock; + + // make sure only one thread uses this function at any given time. + // multiple concurrent threads can have deleterious effects on log + // output, especially when layering structured formats (like JSON) + // on top of a SimpleLogger which is itself not thread-safe. every + // Logger instance should be thread-safe in an ideal world, but we + // cannot really enforce that on a per-logger level at this point. + std::unique_lock _lock(lock); try { writeFull(STDERR_FILENO, s, false); } catch (SysError & e) { |