From d09e13d29daf4223990d8d1ae50013dfcd8e4129 Mon Sep 17 00:00:00 2001 From: Mihir Patel <82491937+LowLevelLore@users.noreply.github.com> Date: Fri, 18 Jul 2025 15:59:07 +0530 Subject: [PATCH] ANSI color sink on Windows --- CMakeLists.txt | 1 + include/spdlog/sinks/ansicolor_sink-inl.h | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 882aa90e..67cf3a20 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -156,6 +156,7 @@ message(STATUS "Build type: " ${CMAKE_BUILD_TYPE}) # Static/Shared library # --------------------------------------------------------------------------------------- set(SPDLOG_SRCS src/spdlog.cpp src/stdout_sinks.cpp src/color_sinks.cpp src/file_sinks.cpp src/async.cpp src/cfg.cpp) +list(APPEND SPDLOG_SRCS include/spdlog/sinks/ansicolor_sink-inl.h) if(NOT SPDLOG_USE_STD_FORMAT AND NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO) list(APPEND SPDLOG_SRCS src/bundled_fmtlib_format.cpp) diff --git a/include/spdlog/sinks/ansicolor_sink-inl.h b/include/spdlog/sinks/ansicolor_sink-inl.h index 6a23f6c7..74f9937f 100644 --- a/include/spdlog/sinks/ansicolor_sink-inl.h +++ b/include/spdlog/sinks/ansicolor_sink-inl.h @@ -10,6 +10,13 @@ #include #include +#if defined(_WIN32) + #include + #include // WriteFile + #include // _get_osfhandle + #include // _fileno +#endif + namespace spdlog { namespace sinks { @@ -113,14 +120,30 @@ SPDLOG_INLINE void ansicolor_sink::set_color_mode_(color_mode mode template SPDLOG_INLINE void ansicolor_sink::print_ccode_( const string_view_t &color_code) const { +#ifdef _WIN32 + DWORD bytes_written = 0; + HANDLE h = + (target_file_ == stdout) ? GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE); + // WriteFile bypasses the extra \r injection + WriteFile(h, color_code.data(), static_cast(color_code.size()), &bytes_written, nullptr); +#else details::os::fwrite_bytes(color_code.data(), color_code.size(), target_file_); +#endif } template SPDLOG_INLINE void ansicolor_sink::print_range_(const memory_buf_t &formatted, size_t start, size_t end) const { +#ifdef _WIN32 + DWORD bytes_written = 0; + HANDLE h = + (target_file_ == stdout) ? GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE); + WriteFile(h, formatted.data() + start, static_cast(end - start), &bytes_written, + nullptr); +#else details::os::fwrite_bytes(formatted.data() + start, end - start, target_file_); +#endif } template