log.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #include "log.h"
  2. #include <Windows.h>
  3. #include <algorithm>
  4. #include <array>
  5. #include <atomic>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <mutex>
  9. #include <shared_mutex>
  10. #include "../filesystem/path.h"
  11. #include "core/threading/srw_lock.h"
  12. #include "snapshot/internal.h"
  13. namespace sunrise::core::log {
  14. namespace {
  15. /** Stable serialized channel names ordered by Channel. */
  16. constexpr std::array<std::string_view, static_cast<std::size_t>(Channel::count)> kChannelNames{
  17. "core", "client", "state", "server", "middleware"};
  18. /** Stable serialized severity names; Level::off is never emitted. */
  19. constexpr std::array<std::string_view, 4> kLevelNames{"error", "warn", "info", "debug"};
  20. /** Optional logs are isolated below the shared generated-artifact directory. */
  21. constexpr std::wstring_view kLogDirectorySuffix = L"\\logs";
  22. /** The active log keeps one stable filename across process starts. */
  23. constexpr std::wstring_view kLogFileSuffix = L"\\sunrise.log";
  24. /** Rotation keeps exactly one prior startup log beside the active file. */
  25. constexpr std::wstring_view kPreviousLogSuffix = L".old";
  26. /** CRLF ends every emitted Windows log record. */
  27. constexpr std::string_view kLineEnding = "\r\n";
  28. /** One trailing null byte is kept for the debugger sink. */
  29. constexpr std::size_t kLineTerminatorBytes = 1;
  30. /** An elapsed line is one event, a duration and an outcome, so it needs less than a full line. */
  31. constexpr std::size_t kElapsedCapacity = 128;
  32. /** Uppercase digits for the hex traces, which are read beside hex dumps of the same bytes. */
  33. constexpr std::string_view kHexDigits = "0123456789ABCDEF";
  34. /** One byte prints as two hex digits, which is the room each appended byte needs. */
  35. constexpr std::size_t kHexDigitsPerByte = 2;
  36. /** Event text stops before the CRLF and the trailing null. */
  37. constexpr std::size_t kEventTextCapacity =
  38. kLineCapacity - kLineEnding.size() - kLineTerminatorBytes;
  39. /** Longest " t=" field: the key plus a 64-bit millisecond count. */
  40. constexpr std::size_t kStampCapacity = 32;
  41. struct LogState {
  42. threading::SrwLock lock{};
  43. std::array<std::atomic<Level>, static_cast<std::size_t>(Channel::count)> levels{};
  44. HANDLE file{INVALID_HANDLE_VALUE};
  45. /** Tick the sinks opened on. Every line carries its offset from this, so stalls are visible. */
  46. ULONGLONG startTick{};
  47. bool debuggerSink{};
  48. bool initialized{};
  49. };
  50. LogState g_log;
  51. /** Threads inside a sink write. Read by anything that suspends process threads. */
  52. std::atomic_int g_writers{};
  53. /**
  54. * Tests one event against its channel threshold.
  55. * @param channel Channel that owns the event.
  56. * @param level Event severity.
  57. * @return True when a valid channel threshold permits the event level.
  58. */
  59. [[nodiscard]] bool enabled(Channel channel, Level level) noexcept {
  60. const auto index = static_cast<std::size_t>(channel);
  61. if (index >= g_log.levels.size() || level == Level::off) {
  62. return false;
  63. }
  64. return static_cast<unsigned char>(level)
  65. <= static_cast<unsigned char>(g_log.levels[index].load(std::memory_order_relaxed));
  66. }
  67. /**
  68. * Appends as much text as fits before one caller-provided content boundary.
  69. * @param line Fixed event-line storage.
  70. * @param offset First free byte.
  71. * @param text Text to append.
  72. * @param limit Exclusive content boundary reserved by the caller.
  73. * @return New first-free byte offset.
  74. */
  75. [[nodiscard]] std::size_t append(std::array<char, kLineCapacity>& line,
  76. std::size_t offset,
  77. std::string_view text,
  78. std::size_t limit) noexcept {
  79. const std::size_t available = offset < limit ? limit - offset : 0;
  80. const std::size_t count = text.size() < available ? text.size() : available;
  81. if (count != 0) {
  82. std::memcpy(line.data() + offset, text.data(), count);
  83. }
  84. return offset + count;
  85. }
  86. /**
  87. * Rotates one prior log and opens a new file below the owned artifact directory.
  88. * @param module Loaded DLL module used to resolve the log directory.
  89. * @return Writable file handle, or INVALID_HANDLE_VALUE on failure.
  90. */
  91. [[nodiscard]] HANDLE open_log_file(void* module) noexcept {
  92. path::Buffer logPath;
  93. if (!path::artifact_directory(module, logPath) || !path::append(logPath, kLogDirectorySuffix)) {
  94. return INVALID_HANDLE_VALUE;
  95. }
  96. if (!CreateDirectoryW(logPath.chars.data(), nullptr)
  97. && GetLastError() != ERROR_ALREADY_EXISTS) {
  98. return INVALID_HANDLE_VALUE;
  99. }
  100. if (!path::append(logPath, kLogFileSuffix)) {
  101. return INVALID_HANDLE_VALUE;
  102. }
  103. path::Buffer oldPath = logPath;
  104. if (!path::append(oldPath, kPreviousLogSuffix)) {
  105. return INVALID_HANDLE_VALUE;
  106. }
  107. // Rotation intentionally keeps only one previous file.
  108. MoveFileExW(logPath.chars.data(), oldPath.chars.data(), MOVEFILE_REPLACE_EXISTING);
  109. return CreateFileW(logPath.chars.data(),
  110. GENERIC_WRITE,
  111. FILE_SHARE_READ,
  112. nullptr,
  113. CREATE_ALWAYS,
  114. FILE_ATTRIBUTE_NORMAL,
  115. nullptr);
  116. }
  117. } // namespace
  118. /** @return Default warning thresholds with debugger output enabled. */
  119. Settings defaults() noexcept {
  120. Settings settings;
  121. settings.levels.fill(Level::warn);
  122. return settings;
  123. }
  124. /** Applies log thresholds and opens the optional file sink. */
  125. bool initialize(void* module, const Settings& settings) noexcept {
  126. const std::lock_guard lock(g_log.lock);
  127. // Resetting under the lifetime lock prevents an admitted writer from repopulating stale view.
  128. snapshot::internal::reset();
  129. if (g_log.file != INVALID_HANDLE_VALUE) {
  130. CloseHandle(g_log.file);
  131. g_log.file = INVALID_HANDLE_VALUE;
  132. }
  133. g_log.initialized = false;
  134. g_log.debuggerSink = settings.debuggerSink;
  135. g_log.startTick = GetTickCount64();
  136. for (std::size_t index = 0; index < g_log.levels.size(); ++index) {
  137. g_log.levels[index].store(settings.levels[index], std::memory_order_relaxed);
  138. }
  139. if (settings.fileSink) {
  140. g_log.file = open_log_file(module);
  141. }
  142. const bool ready = !settings.fileSink || g_log.file != INVALID_HANDLE_VALUE;
  143. g_log.initialized = ready;
  144. if (!ready) {
  145. g_log.debuggerSink = false;
  146. for (std::atomic<Level>& level : g_log.levels) {
  147. level.store(Level::off, std::memory_order_relaxed);
  148. }
  149. }
  150. return ready;
  151. }
  152. /** Closes the optional sink and clears the bounded in-memory view. */
  153. void shutdown() noexcept {
  154. const std::lock_guard lock(g_log.lock);
  155. g_log.initialized = false;
  156. for (std::atomic<Level>& level : g_log.levels) {
  157. level.store(Level::off, std::memory_order_relaxed);
  158. }
  159. g_log.debuggerSink = false;
  160. if (g_log.file != INVALID_HANDLE_VALUE) {
  161. CloseHandle(g_log.file);
  162. g_log.file = INVALID_HANDLE_VALUE;
  163. }
  164. // The same lifetime lock excludes writers until both sinks and retained entries are empty.
  165. snapshot::internal::reset();
  166. }
  167. /** Writes one line straight to the debugger, bypassing the sinks and every threshold. */
  168. void early(std::string_view event) noexcept {
  169. std::array<char, kLineCapacity> line{};
  170. std::size_t length = append(line, 0, "core level=error ", kEventTextCapacity);
  171. length = append(line, length, event, kEventTextCapacity);
  172. std::memcpy(line.data() + length, kLineEnding.data(), kLineEnding.size());
  173. line[length + kLineEnding.size()] = '\0';
  174. g_writers.fetch_add(1, std::memory_order_acq_rel);
  175. OutputDebugStringA(line.data());
  176. g_writers.fetch_sub(1, std::memory_order_acq_rel);
  177. }
  178. /** Reports whether an event would be emitted, so callers can skip the cost of building one. */
  179. bool accepts(Channel channel, Level level) noexcept {
  180. const std::shared_lock lock(g_log.lock);
  181. const bool admitted = g_log.initialized && enabled(channel, level);
  182. return admitted;
  183. }
  184. /** Formats and emits one bounded structured event. */
  185. void write(Channel channel, Level level, std::string_view event) noexcept {
  186. const auto channelIndex = static_cast<std::size_t>(channel);
  187. const auto levelIndex = static_cast<std::size_t>(level);
  188. if (channelIndex >= kChannelNames.size() || levelIndex >= kLevelNames.size()) {
  189. return;
  190. }
  191. const std::shared_lock lock(g_log.lock);
  192. if (!g_log.initialized || !enabled(channel, level)) {
  193. return;
  194. }
  195. std::array<char, kStampCapacity> stamp{};
  196. const int stamped =
  197. std::snprintf(stamp.data(),
  198. stamp.size(),
  199. " t=%llu ",
  200. static_cast<unsigned long long>(GetTickCount64() - g_log.startTick));
  201. std::array<char, kLineCapacity> line{};
  202. std::size_t length = append(line, 0, kChannelNames[channelIndex], kEventTextCapacity);
  203. length = append(line, length, " level=", kEventTextCapacity);
  204. length = append(line, length, kLevelNames[levelIndex], kEventTextCapacity);
  205. length = append(line,
  206. length,
  207. stamped > 0 ? std::string_view(stamp.data(), static_cast<std::size_t>(stamped))
  208. : std::string_view(" "),
  209. kEventTextCapacity);
  210. length = append(line, length, event, kEventTextCapacity);
  211. const std::size_t snapshotLength = length;
  212. std::memcpy(line.data() + length, kLineEnding.data(), kLineEnding.size());
  213. length += kLineEnding.size();
  214. line[length] = '\0';
  215. // The admission lock stays held across the sinks and the snapshot record.
  216. g_writers.fetch_add(1, std::memory_order_acq_rel);
  217. if (g_log.debuggerSink) {
  218. OutputDebugStringA(line.data());
  219. }
  220. if (g_log.file != INVALID_HANDLE_VALUE) {
  221. DWORD written = 0;
  222. WriteFile(g_log.file, line.data(), static_cast<DWORD>(length), &written, nullptr);
  223. }
  224. g_writers.fetch_sub(1, std::memory_order_acq_rel);
  225. // Record after sink writes while the shared lifetime lock still excludes shutdown reset.
  226. snapshot::internal::record(channel, level, std::string_view(line.data(), snapshotLength));
  227. }
  228. /** Formats and emits one debug event carrying a duration in the ms field. */
  229. void write_elapsed(Channel channel,
  230. std::string_view event,
  231. unsigned long long startedTick,
  232. std::string_view result) noexcept {
  233. if (!accepts(channel, Level::debug)) {
  234. return;
  235. }
  236. const unsigned long long elapsed = GetTickCount64() - startedTick;
  237. std::array<char, kElapsedCapacity> line{};
  238. const int written = std::snprintf(line.data(),
  239. line.size(),
  240. "%.*s ms=%llu result=%.*s",
  241. static_cast<int>(event.size()),
  242. event.data(),
  243. elapsed,
  244. static_cast<int>(result.size()),
  245. result.data());
  246. if (written <= 0) {
  247. return;
  248. }
  249. // snprintf reports the length before truncation, so the emitted view is clamped to the buffer.
  250. const auto length =
  251. std::min(static_cast<std::size_t>(written), line.size() - kLineTerminatorBytes);
  252. write(channel, Level::debug, {line.data(), length});
  253. }
  254. /** Appends bytes as uppercase hex to a line that already holds its key prefix. */
  255. bool append_hex(std::span<char> line,
  256. std::size_t& length,
  257. std::span<const std::byte> bytes) noexcept {
  258. for (const std::byte byte : bytes) {
  259. if (length + kHexDigitsPerByte >= line.size()) {
  260. return false;
  261. }
  262. const auto value = std::to_integer<unsigned>(byte);
  263. line[length++] = kHexDigits[(value >> 4U) & 0xFU];
  264. line[length++] = kHexDigits[value & 0xFU];
  265. }
  266. return true;
  267. }
  268. /** @return True while a sink write is in progress. */
  269. bool writers_active() noexcept {
  270. return g_writers.load(std::memory_order_acquire) != 0;
  271. }
  272. } // namespace sunrise::core::log