msvc_sink.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright(c) 2016 Alexander Dalshov & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #if defined(_WIN32)
  5. # include <spdlog/details/null_mutex.h>
  6. # include <spdlog/sinks/base_sink.h>
  7. # include <mutex>
  8. # include <string>
  9. // Avoid including windows.h (https://stackoverflow.com/a/30741042)
  10. extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char *lpOutputString);
  11. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  12. namespace spdlog {
  13. namespace sinks {
  14. /*
  15. * MSVC sink (logging using OutputDebugStringA)
  16. */
  17. template<typename Mutex>
  18. class msvc_sink : public base_sink<Mutex>
  19. {
  20. public:
  21. msvc_sink() = default;
  22. msvc_sink(bool check_ebugger_present)
  23. : check_debbugger_present_{check_ebugger_present} {};
  24. protected:
  25. void sink_it_(const details::log_msg &msg) override
  26. {
  27. if (check_debbugger_present_ && !IsDebuggerPresent())
  28. {
  29. return;
  30. }
  31. memory_buf_t formatted;
  32. base_sink<Mutex>::formatter_->format(msg, formatted);
  33. formatted.push_back('\0'); // add a null terminator for OutputDebugStringA
  34. OutputDebugStringA(formatted.data());
  35. }
  36. void flush_() override {}
  37. bool check_debbugger_present_ = true;
  38. };
  39. using msvc_sink_mt = msvc_sink<std::mutex>;
  40. using msvc_sink_st = msvc_sink<details::null_mutex>;
  41. using windebug_sink_mt = msvc_sink_mt;
  42. using windebug_sink_st = msvc_sink_st;
  43. } // namespace sinks
  44. } // namespace spdlog
  45. #endif