Skip to content

Commit

Permalink
Add consolute mutex support to wincolor sink
Browse files Browse the repository at this point in the history
  • Loading branch information
gabime committed Nov 10, 2024
1 parent bfe2116 commit 3c4b1ce
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 11 additions & 1 deletion include/spdlog/sinks/wincolor_sink-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace spdlog {
namespace sinks {
template <typename Mutex>
SPDLOG_INLINE wincolor_sink<Mutex>::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
Expand Down Expand Up @@ -45,6 +45,12 @@ void SPDLOG_INLINE wincolor_sink<Mutex>::set_color(level::level_enum level,
colors_[static_cast<size_t>(level)] = color;
}

template <typename Mutex>
void SPDLOG_INLINE wincolor_sink<Mutex>::set_console_mutex(std::mutex* mutex) {
std::lock_guard<Mutex> lock(base_t::mutex_);
console_mutex_ = mutex;
}

template <typename Mutex>
void SPDLOG_INLINE wincolor_sink<Mutex>::sink_it_(const details::log_msg &msg) {
if (out_handle_ == nullptr || out_handle_ == INVALID_HANDLE_VALUE) {
Expand All @@ -54,6 +60,10 @@ void SPDLOG_INLINE wincolor_sink<Mutex>::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<std::mutex>(*console_mutex_)
: std::unique_lock<std::mutex>();

if (should_do_colors_ && msg.color_range_end > msg.color_range_start) {
// before color range
print_range_(formatted, 0, msg.color_range_start);
Expand Down
2 changes: 2 additions & 0 deletions include/spdlog/sinks/wincolor_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@ class wincolor_sink : public base_sink<Mutex> {
// 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<std::uint16_t, level::n_levels> colors_;
std::mutex *console_mutex_;

void sink_it_(const details::log_msg &msg) final override;
void flush_() final override;
Expand Down

0 comments on commit 3c4b1ce

Please sign in to comment.