69 lines
2.0 KiB
C
Raw Normal View History

// Copyright(c) 2016 Alexander Dalshov & spdlog contributors.
2021-07-08 07:07:27 -07:00
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#if defined(_WIN32)
2021-07-08 07:07:27 -07:00
2024-02-04 13:43:17 +01:00
#include <spdlog/details/null_mutex.h>
#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
#include <spdlog/details/os.h>
#endif
#include <spdlog/sinks/base_sink.h>
2021-07-08 07:07:27 -07:00
2024-02-04 13:43:17 +01:00
#include <mutex>
#include <string>
2021-07-08 07:07:27 -07:00
2024-02-04 13:43:17 +01:00
// Avoid including windows.h (https://stackoverflow.com/a/30741042)
#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
2023-09-17 20:37:44 +02:00
extern "C" __declspec(dllimport) void __stdcall OutputDebugStringW(const wchar_t *lpOutputString);
2024-02-04 13:43:17 +01:00
#else
2021-07-08 07:07:27 -07:00
extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char *lpOutputString);
2024-02-04 13:43:17 +01:00
#endif
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
2021-07-08 07:07:27 -07:00
namespace spdlog {
namespace sinks {
/*
* MSVC sink (logging using OutputDebugStringA)
*/
2024-02-04 13:43:17 +01:00
template <typename Mutex>
class msvc_sink : public base_sink<Mutex> {
2021-07-08 07:07:27 -07:00
public:
msvc_sink() = default;
2023-09-17 20:37:44 +02:00
msvc_sink(bool check_debugger_present)
: check_debugger_present_{check_debugger_present} {};
2021-07-08 07:07:27 -07:00
protected:
2024-02-04 13:43:17 +01:00
void sink_it_(const details::log_msg &msg) override {
if (check_debugger_present_ && !IsDebuggerPresent()) {
return;
}
2021-07-08 07:07:27 -07:00
memory_buf_t formatted;
base_sink<Mutex>::formatter_->format(msg, formatted);
2024-02-04 13:43:17 +01:00
formatted.push_back('\0'); // add a null terminator for OutputDebugString
#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
2023-09-17 20:37:44 +02:00
wmemory_buf_t wformatted;
details::os::utf8_to_wstrbuf(string_view_t(formatted.data(), formatted.size()), wformatted);
OutputDebugStringW(wformatted.data());
2024-02-04 13:43:17 +01:00
#else
OutputDebugStringA(formatted.data());
2024-02-04 13:43:17 +01:00
#endif
2021-07-08 07:07:27 -07:00
}
void flush_() override {}
2023-09-17 20:37:44 +02:00
bool check_debugger_present_ = true;
2021-07-08 07:07:27 -07:00
};
using msvc_sink_mt = msvc_sink<std::mutex>;
using msvc_sink_st = msvc_sink<details::null_mutex>;
using windebug_sink_mt = msvc_sink_mt;
using windebug_sink_st = msvc_sink_st;
2024-02-04 13:43:17 +01:00
} // namespace sinks
} // namespace spdlog
2021-07-08 07:07:27 -07:00
#endif