win_eventlog_sink.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. // Writing to Windows Event Log requires the registry entries below to be present, with the
  4. // following modifications:
  5. // 1. <log_name> should be replaced with your log name (e.g. your application name)
  6. // 2. <source_name> should be replaced with the specific source name and the key should be
  7. // duplicated for
  8. // each source used in the application
  9. //
  10. // Since typically modifications of this kind require elevation, it's better to do it as a part of
  11. // setup procedure. The snippet below uses mscoree.dll as the message file as it exists on most of
  12. // the Windows systems anyway and happens to contain the needed resource.
  13. //
  14. // You can also specify a custom message file if needed.
  15. // Please refer to Event Log functions descriptions in MSDN for more details on custom message
  16. // files.
  17. /*---------------------------------------------------------------------------------------
  18. Windows Registry Editor Version 5.00
  19. [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\<log_name>]
  20. [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\<log_name>\<source_name>]
  21. "TypesSupported"=dword:00000007
  22. "EventMessageFile"=hex(2):25,00,73,00,79,00,73,00,74,00,65,00,6d,00,72,00,6f,\
  23. 00,6f,00,74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,\
  24. 5c,00,6d,00,73,00,63,00,6f,00,72,00,65,00,65,00,2e,00,64,00,6c,00,6c,00,00,\
  25. 00
  26. -----------------------------------------------------------------------------------------*/
  27. #pragma once
  28. #include <spdlog/details/null_mutex.h>
  29. #include <spdlog/sinks/base_sink.h>
  30. #include <spdlog/details/windows_include.h>
  31. #include <winbase.h>
  32. #include <mutex>
  33. #include <string>
  34. #include <vector>
  35. namespace spdlog {
  36. namespace sinks {
  37. namespace win_eventlog {
  38. namespace internal {
  39. struct local_alloc_t {
  40. HLOCAL hlocal_;
  41. SPDLOG_CONSTEXPR local_alloc_t() SPDLOG_NOEXCEPT : hlocal_(nullptr) {}
  42. local_alloc_t(local_alloc_t const &) = delete;
  43. local_alloc_t &operator=(local_alloc_t const &) = delete;
  44. ~local_alloc_t() SPDLOG_NOEXCEPT {
  45. if (hlocal_) {
  46. LocalFree(hlocal_);
  47. }
  48. }
  49. };
  50. /** Windows error */
  51. struct win32_error : public spdlog_ex {
  52. /** Formats an error report line: "user-message: error-code (system message)" */
  53. static std::string format(std::string const &user_message, DWORD error_code = GetLastError()) {
  54. std::string system_message;
  55. local_alloc_t format_message_result{};
  56. auto format_message_succeeded =
  57. ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  58. FORMAT_MESSAGE_IGNORE_INSERTS,
  59. nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  60. (LPSTR)&format_message_result.hlocal_, 0, nullptr);
  61. if (format_message_succeeded && format_message_result.hlocal_) {
  62. system_message = fmt_lib::format(" ({})", (LPSTR)format_message_result.hlocal_);
  63. }
  64. return fmt_lib::format("{}: {}{}", user_message, error_code, system_message);
  65. }
  66. explicit win32_error(std::string const &func_name, DWORD error = GetLastError())
  67. : spdlog_ex(format(func_name, error)) {}
  68. };
  69. /** Wrapper for security identifiers (SID) on Windows */
  70. struct sid_t {
  71. std::vector<char> buffer_;
  72. public:
  73. sid_t() {}
  74. /** creates a wrapped SID copy */
  75. static sid_t duplicate_sid(PSID psid) {
  76. if (!::IsValidSid(psid)) {
  77. throw_spdlog_ex("sid_t::sid_t(): invalid SID received");
  78. }
  79. auto const sid_length{::GetLengthSid(psid)};
  80. sid_t result;
  81. result.buffer_.resize(sid_length);
  82. if (!::CopySid(sid_length, (PSID)result.as_sid(), psid)) {
  83. SPDLOG_THROW(win32_error("CopySid"));
  84. }
  85. return result;
  86. }
  87. /** Retrieves pointer to the internal buffer contents as SID* */
  88. SID *as_sid() const { return buffer_.empty() ? nullptr : (SID *)buffer_.data(); }
  89. /** Get SID for the current user */
  90. static sid_t get_current_user_sid() {
  91. /* create and init RAII holder for process token */
  92. struct process_token_t {
  93. HANDLE token_handle_ = INVALID_HANDLE_VALUE;
  94. explicit process_token_t(HANDLE process) {
  95. if (!::OpenProcessToken(process, TOKEN_QUERY, &token_handle_)) {
  96. SPDLOG_THROW(win32_error("OpenProcessToken"));
  97. }
  98. }
  99. ~process_token_t() { ::CloseHandle(token_handle_); }
  100. } current_process_token(
  101. ::GetCurrentProcess()); // GetCurrentProcess returns pseudohandle, no leak here!
  102. // Get the required size, this is expected to fail with ERROR_INSUFFICIENT_BUFFER and return
  103. // the token size
  104. DWORD tusize = 0;
  105. if (::GetTokenInformation(current_process_token.token_handle_, TokenUser, NULL, 0,
  106. &tusize)) {
  107. SPDLOG_THROW(win32_error("GetTokenInformation should fail"));
  108. }
  109. // get user token
  110. std::vector<unsigned char> buffer(static_cast<size_t>(tusize));
  111. if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser,
  112. (LPVOID)buffer.data(), tusize, &tusize)) {
  113. SPDLOG_THROW(win32_error("GetTokenInformation"));
  114. }
  115. // create a wrapper of the SID data as stored in the user token
  116. return sid_t::duplicate_sid(((TOKEN_USER *)buffer.data())->User.Sid);
  117. }
  118. };
  119. struct eventlog {
  120. static WORD get_event_type(details::log_msg const &msg) {
  121. switch (msg.level) {
  122. case level::trace:
  123. case level::debug:
  124. return EVENTLOG_SUCCESS;
  125. case level::info:
  126. return EVENTLOG_INFORMATION_TYPE;
  127. case level::warn:
  128. return EVENTLOG_WARNING_TYPE;
  129. case level::err:
  130. case level::critical:
  131. case level::off:
  132. return EVENTLOG_ERROR_TYPE;
  133. default:
  134. return EVENTLOG_INFORMATION_TYPE;
  135. }
  136. }
  137. static WORD get_event_category(details::log_msg const &msg) { return (WORD)msg.level; }
  138. };
  139. } // namespace internal
  140. /*
  141. * Windows Event Log sink
  142. */
  143. template <typename Mutex>
  144. class win_eventlog_sink : public base_sink<Mutex> {
  145. private:
  146. HANDLE hEventLog_{NULL};
  147. internal::sid_t current_user_sid_;
  148. std::string source_;
  149. DWORD event_id_;
  150. HANDLE event_log_handle() {
  151. if (!hEventLog_) {
  152. hEventLog_ = ::RegisterEventSourceA(nullptr, source_.c_str());
  153. if (!hEventLog_ || hEventLog_ == (HANDLE)ERROR_ACCESS_DENIED) {
  154. SPDLOG_THROW(internal::win32_error("RegisterEventSource"));
  155. }
  156. }
  157. return hEventLog_;
  158. }
  159. protected:
  160. void sink_it_(const details::log_msg &msg) override {
  161. using namespace internal;
  162. bool succeeded;
  163. memory_buf_t formatted;
  164. base_sink<Mutex>::formatter_->format(msg, formatted);
  165. formatted.push_back('\0');
  166. #ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
  167. wmemory_buf_t buf;
  168. details::os::utf8_to_wstrbuf(string_view_t(formatted.data(), formatted.size()), buf);
  169. LPCWSTR lp_wstr = buf.data();
  170. succeeded = static_cast<bool>(::ReportEventW(
  171. event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg),
  172. event_id_, current_user_sid_.as_sid(), 1, 0, &lp_wstr, nullptr));
  173. #else
  174. LPCSTR lp_str = formatted.data();
  175. succeeded = static_cast<bool>(::ReportEventA(
  176. event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg),
  177. event_id_, current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr));
  178. #endif
  179. if (!succeeded) {
  180. SPDLOG_THROW(win32_error("ReportEvent"));
  181. }
  182. }
  183. void flush_() override {}
  184. public:
  185. win_eventlog_sink(std::string const &source,
  186. DWORD event_id = 1000 /* according to mscoree.dll */)
  187. : source_(source),
  188. event_id_(event_id) {
  189. try {
  190. current_user_sid_ = internal::sid_t::get_current_user_sid();
  191. } catch (...) {
  192. // get_current_user_sid() is unlikely to fail and if it does, we can still proceed
  193. // without current_user_sid but in the event log the record will have no user name
  194. }
  195. }
  196. ~win_eventlog_sink() {
  197. if (hEventLog_) DeregisterEventSource(hEventLog_);
  198. }
  199. };
  200. } // namespace win_eventlog
  201. using win_eventlog_sink_mt = win_eventlog::win_eventlog_sink<std::mutex>;
  202. using win_eventlog_sink_st = win_eventlog::win_eventlog_sink<details::null_mutex>;
  203. } // namespace sinks
  204. } // namespace spdlog