diff --git a/include/spdlog/sinks/ansicolor_sink-inl.h b/include/spdlog/sinks/ansicolor_sink-inl.h index b2b3e604..1a4ac5a7 100644 --- a/include/spdlog/sinks/ansicolor_sink-inl.h +++ b/include/spdlog/sinks/ansicolor_sink-inl.h @@ -15,7 +15,7 @@ namespace sinks { template SPDLOG_INLINE ansicolor_sink::ansicolor_sink(FILE *target_file, color_mode mode) - : target_file_(target_file) + : target_file_(target_file), console_mutex_(nullptr) { set_color_mode_(mode); colors_.at(level::trace) = to_string_(white); @@ -42,6 +42,10 @@ SPDLOG_INLINE void ansicolor_sink::sink_it_(const details::log_msg &msg) msg.color_range_end = 0; memory_buf_t formatted; base_sink::formatter_->format(msg, formatted); + auto console_lock = console_mutex_ != nullptr ? + std::unique_lock(*console_mutex_) : + std::unique_lock(); + if (should_do_colors_ && msg.color_range_end > msg.color_range_start) { // before color range print_range_(formatted, 0, msg.color_range_start); @@ -60,6 +64,9 @@ SPDLOG_INLINE void ansicolor_sink::sink_it_(const details::log_msg &msg) template SPDLOG_INLINE void ansicolor_sink::flush_() { + auto console_lock = console_mutex_ != nullptr ? + std::unique_lock(*console_mutex_) : + std::unique_lock(); fflush(target_file_); } @@ -74,6 +81,12 @@ SPDLOG_INLINE void ansicolor_sink::set_color_mode(color_mode mode) { set_color_mode_(mode); } +template +SPDLOG_INLINE void ansicolor_sink::set_console_mutex(std::mutex* mutex) { + std::lock_guard lock(base_sink::mutex_); + console_mutex_ = mutex; +} + template SPDLOG_INLINE void ansicolor_sink::set_color_mode_(color_mode mode) { switch (mode) { diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h index bca0d05f..3507ecc7 100644 --- a/include/spdlog/sinks/ansicolor_sink.h +++ b/include/spdlog/sinks/ansicolor_sink.h @@ -7,6 +7,7 @@ #include #include +#include #include namespace spdlog { @@ -33,6 +34,7 @@ public: void set_color(level::level_enum color_level, string_view_t color); void set_color_mode(color_mode mode); + void set_console_mutex(std::mutex *console_mutex); bool should_color(); // Formatting codes const string_view_t reset = "\033[m"; @@ -73,6 +75,7 @@ protected: FILE *target_file_; bool should_do_colors_; std::array colors_; + std::mutex *console_mutex_; void sink_it_(const details::log_msg &msg) override; void flush_() override;