diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h index 7d25ba1f..7f59c763 100644 --- a/include/spdlog/sinks/wincolor_sink-inl.h +++ b/include/spdlog/sinks/wincolor_sink-inl.h @@ -17,7 +17,7 @@ namespace spdlog { namespace sinks { template SPDLOG_INLINE wincolor_sink::wincolor_sink(void *out_handle, color_mode mode) - : out_handle_(out_handle) { + : out_handle_(out_handle), console_mutex_(nullptr) { set_color_mode_impl(mode); // set level colors colors_[level::trace] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white @@ -45,6 +45,12 @@ void SPDLOG_INLINE wincolor_sink::set_color(level::level_enum level, colors_[static_cast(level)] = color; } +template +void SPDLOG_INLINE wincolor_sink::set_console_mutex(std::mutex* mutex) { + std::lock_guard lock(base_t::mutex_); + console_mutex_ = mutex; +} + template void SPDLOG_INLINE wincolor_sink::sink_it_(const details::log_msg &msg) { if (out_handle_ == nullptr || out_handle_ == INVALID_HANDLE_VALUE) { @@ -54,6 +60,10 @@ void SPDLOG_INLINE wincolor_sink::sink_it_(const details::log_msg &msg) { msg.color_range_end = 0; memory_buf_t formatted; base_t::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); diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h index 99a12a1e..c133bd18 100644 --- a/include/spdlog/sinks/wincolor_sink.h +++ b/include/spdlog/sinks/wincolor_sink.h @@ -30,11 +30,13 @@ public: // change the color for the given level void set_color(level::level_enum level, std::uint16_t color); void set_color_mode(color_mode mode); + void set_console_mutex(std::mutex *console_mutex); protected: void *out_handle_; bool should_do_colors_; std::array colors_; + std::mutex *console_mutex_; void sink_it_(const details::log_msg &msg) final override; void flush_() final override;