log.cpp 12 KB

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