diff --git a/modules/ANSUtilities/ANSUtilities.cpp b/modules/ANSUtilities/ANSUtilities.cpp index 10ee816..63b9b2a 100644 --- a/modules/ANSUtilities/ANSUtilities.cpp +++ b/modules/ANSUtilities/ANSUtilities.cpp @@ -1,6 +1,8 @@ #include "ANSUtilities.h" #ifdef _WIN32 #include +#include // EvtQuery / EvtRender for GetANSLoggerErrorEvents +#pragma comment(lib, "wevtapi.lib") #endif #include #include @@ -1309,6 +1311,169 @@ namespace ANSCENTER } return result; } + // ==================================================================== + // GetANSLoggerErrorEvents + // + // Reads every Error-level event written by the "ANSLogger" source in + // the Application channel using the modern winevt API. Events are + // produced by WindowsEventSink in ANSLicensingSystem (see + // ANSLicense.cpp::ReportEventW) — each carries a single inserted + // string in .... + // + // DebugView: filter "[EVTLOG]". + // ==================================================================== + std::string ANSUtilities::GetANSLoggerErrorEvents(bool clearAfterRead) { + // XPath: Provider name "ANSLogger" AND Level 2 (EVENTLOG_ERROR_TYPE). + // Forward direction keeps chronological insertion order so output + // matches a fresh "oldest first" scroll through Event Viewer. + constexpr const wchar_t* kQuery = + L"*[System[Provider[@Name='ANSLogger'] and Level=2]]"; + + EVT_HANDLE hResults = EvtQuery(nullptr, L"Application", kQuery, + EvtQueryChannelPath | EvtQueryForwardDirection); + if (!hResults) { + ANS_DBG("EVTLOG", "EvtQuery failed err=%lu", GetLastError()); + return std::string(); + } + + std::string out; + constexpr DWORD kBatch = 64; + EVT_HANDLE events[kBatch]; + DWORD returned = 0; + + // Render-buffer reused across events to avoid per-event allocation. + std::vector buf(8192); + + while (EvtNext(hResults, kBatch, events, INFINITE, 0, &returned)) { + for (DWORD i = 0; i < returned; ++i) { + DWORD used = 0, propCount = 0; + if (!EvtRender(nullptr, events[i], EvtRenderEventXml, + static_cast(buf.size() * sizeof(wchar_t)), + buf.data(), &used, &propCount)) { + DWORD lastErr = GetLastError(); + if (lastErr == ERROR_INSUFFICIENT_BUFFER) { + buf.resize(used / sizeof(wchar_t) + 1); + if (!EvtRender(nullptr, events[i], EvtRenderEventXml, + static_cast(buf.size() * sizeof(wchar_t)), + buf.data(), &used, &propCount)) { + EvtClose(events[i]); + continue; + } + } else { + ANS_DBG("EVTLOG", "EvtRender failed err=%lu", lastErr); + EvtClose(events[i]); + continue; + } + } + std::wstring xml(buf.data()); + + // ---- TimeCreated SystemTime='2026-05-18T11:52:07.123Z' ---- + // EvtRender produces either single- or double-quoted attrs + // depending on Windows version, so handle both. + std::string formattedTime; + auto tcPos = xml.find(L"TimeCreated SystemTime="); + if (tcPos != std::wstring::npos) { + tcPos += 23; // length of "TimeCreated SystemTime=" + if (tcPos < xml.size() && + (xml[tcPos] == L'"' || xml[tcPos] == L'\'')) { + wchar_t quote = xml[tcPos]; + ++tcPos; + auto endQuote = xml.find(quote, tcPos); + if (endQuote != std::wstring::npos) { + std::wstring iso = xml.substr(tcPos, endQuote - tcPos); + int Y = 0, M = 0, D = 0, h = 0, m = 0, s = 0; + if (swscanf_s(iso.c_str(), L"%d-%d-%dT%d:%d:%d", + &Y, &M, &D, &h, &m, &s) == 6) { + SYSTEMTIME utc{}; + utc.wYear = (WORD)Y; utc.wMonth = (WORD)M; utc.wDay = (WORD)D; + utc.wHour = (WORD)h; utc.wMinute = (WORD)m; utc.wSecond = (WORD)s; + SYSTEMTIME local{}; + if (!SystemTimeToTzSpecificLocalTime(nullptr, &utc, &local)) { + local = utc; // fallback: show UTC + } + wchar_t dateBuf[64] = {}, timeBuf[64] = {}; + GetDateFormatW(LOCALE_USER_DEFAULT, 0, &local, nullptr, + dateBuf, _countof(dateBuf)); + GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &local, nullptr, + timeBuf, _countof(timeBuf)); + std::wstring combined = std::wstring(dateBuf) + L" " + timeBuf; + int need = WideCharToMultiByte(CP_UTF8, 0, + combined.c_str(), -1, nullptr, 0, nullptr, nullptr); + if (need > 1) { + formattedTime.resize(need - 1); + WideCharToMultiByte(CP_UTF8, 0, combined.c_str(), -1, + formattedTime.data(), need, nullptr, nullptr); + } + } // close: if (swscanf_s ... == 6) + } // close: if (endQuote != npos) + } // close: if (xml[tcPos] is quote) + } // close: if (tcPos != npos) + + // ---- Concatenate every ... inside ---- + // ReportEventW with N strings produces N consecutive + // elements. ANSLogger sends just one but we handle the general + // case so the function works for other sources too. + std::wstring wdata; + auto edStart = xml.find(L"", edStart); + if (edStart != std::wstring::npos && edEnd != std::wstring::npos) { + auto bodyEnd = edEnd; + auto cursor = edStart; + while (cursor < bodyEnd) { + auto dOpen = xml.find(L"= bodyEnd) break; + auto dGt = xml.find(L'>', dOpen); + if (dGt == std::wstring::npos || dGt >= bodyEnd) break; + auto dClose = xml.find(L"", dGt); + if (dClose == std::wstring::npos || dClose > bodyEnd) break; + if (!wdata.empty()) wdata += L' '; + wdata.append(xml, dGt + 1, dClose - dGt - 1); + cursor = dClose + sizeof("") - 1; + } + } + std::string utf8Data; + if (!wdata.empty()) { + int need = WideCharToMultiByte(CP_UTF8, 0, wdata.c_str(), -1, + nullptr, 0, nullptr, nullptr); + if (need > 1) { + utf8Data.resize(need - 1); + WideCharToMultiByte(CP_UTF8, 0, wdata.c_str(), -1, + utf8Data.data(), need, nullptr, nullptr); + } + } + + // Flatten embedded CR/LF in the message body so the + // "one line per event" contract holds. ChilkatLog and + // similar multi-line payloads otherwise break callers + // that split on '\n'. + for (char& c : utf8Data) if (c == '\r' || c == '\n') c = ' '; + + out += formattedTime; + out += ": "; + out += utf8Data; + out += '\n'; + + EvtClose(events[i]); + } + } + DWORD lastErr = GetLastError(); + if (lastErr != ERROR_NO_MORE_ITEMS) { + ANS_DBG("EVTLOG", "EvtNext stopped err=%lu", lastErr); + } + EvtClose(hResults); + + if (clearAfterRead) { + // Clears the entire Application channel — see header warning. + if (!EvtClearLog(nullptr, L"Application", nullptr, 0)) { + DWORD e = GetLastError(); + ANS_DBG("EVTLOG", "EvtClearLog failed err=%lu (need admin)", e); + } else { + ANS_DBG("EVTLOG", "EvtClearLog: Application channel cleared"); + } + } + return out; + } + } // namespace ANSCENTER // ============================================================================ diff --git a/modules/ANSUtilities/ANSUtilities.h b/modules/ANSUtilities/ANSUtilities.h index 70d96d4..5dd9cdf 100644 --- a/modules/ANSUtilities/ANSUtilities.h +++ b/modules/ANSUtilities/ANSUtilities.h @@ -155,6 +155,20 @@ namespace ANSCENTER { // Reverses DoubleEscapeUnicode so other languages can parse \uXXXX correctly. static std::string UnescapeDoubleEscapedUnicode(const std::string& str); + // Read every Error-level event from "ANSLogger" in the Windows + // Application event log. Output: one line per event in the form + // "
: \n" + // Time is converted to the user's local timezone and formatted + // using LOCALE_USER_DEFAULT (matches Event Viewer's display). + // + // If `clearAfterRead` is true, calls EvtClearLog on the entire + // Application channel after reading. WARNING: this wipes every + // event from every source in the Application log, not just + // ANSLogger entries — there is no per-event delete API in + // Windows. Requires Administrator privileges; without elevation + // the clear silently fails (events are still returned). + [[nodiscard]] static std::string GetANSLoggerErrorEvents(bool clearAfterRead = false); + // Scan the local network for AIBOX / ANSVIS servers. // Runs two strategies in parallel and merges results by IP: // 1) UDP multicast probe to 230.50.200.150:58839 (with subnet @@ -376,6 +390,14 @@ extern "C" ANSULT_API int RebootSystem(); extern "C" ANSULT_API int ScanANSDevices(int timeoutMs, LStrHandle resultJson); extern "C" ANSULT_API int ScanANSDevicesCpp(int timeoutMs, std::string& resultJson); +// Read all Error-level events from "ANSLogger" in the Windows Application +// event log. Returns a UTF-8 string with one event per line: +// "
: \n" +// `clearAfterRead` != 0 clears the entire Application channel afterwards +// (requires Administrator; see header comment on the C++ method). +extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle result); +extern "C" ANSULT_API int GetANSLoggerErrorEventsCpp(int clearAfterRead, std::string& result); + // Unicode conversion utilities for LabVIEW extern "C" ANSULT_API int ANSConvertUTF8ToUTF16LE(const char* utf8Str, LStrHandle result, int includeBOM = 1); extern "C" ANSULT_API int ANSDecodeJsonUnicodeToUTF16LE(const char* escapedStr, LStrHandle result); diff --git a/modules/ANSUtilities/CMakeLists.txt b/modules/ANSUtilities/CMakeLists.txt index 989eb88..6b92930 100644 --- a/modules/ANSUtilities/CMakeLists.txt +++ b/modules/ANSUtilities/CMakeLists.txt @@ -22,8 +22,9 @@ target_link_libraries(ANSUtilities if(WIN32) # WIN_COMMON_LIBS covers ws2_32, iphlpapi, etc. winhttp is needed for the - # ScanDevices HTTP /ServerApi sweep. - target_link_libraries(ANSUtilities PRIVATE ${WIN_COMMON_LIBS} crypt32 winhttp) + # ScanDevices HTTP /ServerApi sweep. wevtapi is needed for + # GetANSLoggerErrorEvents (EvtQuery / EvtRender / EvtClearLog). + target_link_libraries(ANSUtilities PRIVATE ${WIN_COMMON_LIBS} crypt32 winhttp wevtapi) endif() target_compile_definitions(ANSUtilities PRIVATE UNICODE _UNICODE ANSUTILITIES_EXPORTS) diff --git a/modules/ANSUtilities/dllmain.cpp b/modules/ANSUtilities/dllmain.cpp index 53ed966..857c63f 100644 --- a/modules/ANSUtilities/dllmain.cpp +++ b/modules/ANSUtilities/dllmain.cpp @@ -3052,3 +3052,44 @@ extern "C" ANSULT_API int ScanANSDevices(int timeoutMs, LStrHandle resultJson) { } catch (...) { return -1; } } + +// --------------------------------------------------------------------------- +// GetANSLoggerErrorEvents — read Error-level events from the ANSLogger source +// in the Windows Application event log. Returns 1 on success (string may be +// empty if no events match), 0 on internal failure. +// `clearAfterRead != 0` triggers EvtClearLog on the entire Application +// channel — see ANSUtilities.h header comment for caveats. +// --------------------------------------------------------------------------- +extern "C" ANSULT_API int GetANSLoggerErrorEventsCpp(int clearAfterRead, std::string& result) { + ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsCpp: clearAfterRead=%d", clearAfterRead); + try { + result = ANSCENTER::ANSUtilities::GetANSLoggerErrorEvents(clearAfterRead != 0); + return 1; + } + catch (const std::exception& e) { + ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsCpp threw: %s", e.what()); + result.clear(); + return 0; + } + catch (...) { + ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsCpp threw unknown"); + result.clear(); + return 0; + } +} + +extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle result) { + ANS_DBG("ANSUTIL", "GetANSLoggerErrorEvents: clearAfterRead=%d", clearAfterRead); + if (!result) return -1; + try { + std::string s; + GetANSLoggerErrorEventsCpp(clearAfterRead, s); + int size = static_cast(s.size()); + MgErr error = DSSetHandleSize(result, sizeof(int32) + size * sizeof(uChar)); + if (error != noErr) return -2; + (*result)->cnt = size; + if (size > 0) memcpy((*result)->str, s.data(), size); + return 1; + } + catch (...) { return -1; } +} diff --git a/tests/ANSUtilities-UnitTest/ANSUtilities-UnitTest.cpp b/tests/ANSUtilities-UnitTest/ANSUtilities-UnitTest.cpp index 3866a81..c7090e4 100644 --- a/tests/ANSUtilities-UnitTest/ANSUtilities-UnitTest.cpp +++ b/tests/ANSUtilities-UnitTest/ANSUtilities-UnitTest.cpp @@ -419,6 +419,90 @@ int ScanDevicesTest() return static_cast(devices.size()); } +// ============================================================================ +// Example: ANSCENTER::ANSUtilities::GetANSLoggerErrorEvents +// +// Reads every Error-level event written by the "ANSLogger" source in the +// Windows Application event log. Output is a UTF-8 string with one event +// per line in the form: +// "
: \n" +// +// Three usage patterns are demonstrated below: +// 1. Read everything as one blob — simplest, what LabVIEW will do. +// 2. Iterate line-by-line and split out timestamp + message — useful for +// programmatic filtering, alerting, or writing to your own sink. +// 3. Destructive clear (commented out) — wipes the entire Application +// channel; only use if you genuinely want every event from every +// source removed. Requires Administrator privileges. +// +// To verify against Event Viewer: +// eventvwr.msc → Windows Logs → Application → Filter Current Log: +// Event sources = ANSLogger, Event level = Error +// The number this function returns must match Event Viewer's "Number of +// events" line shown above the list. +// ============================================================================ +int GetEventLogErrorsTest() +{ + std::cout << "\n===== GetANSLoggerErrorEvents (Windows Event Log) =====" << std::endl; + + // ── 1. Read every Error event from ANSLogger ──────────────────────────── + const bool kClearAfterRead = false; // NEVER true unless you really mean it + std::string events = ANSCENTER::ANSUtilities::GetANSLoggerErrorEvents(kClearAfterRead); + + // Count events (one per newline). + int lineCount = 0; + for (char c : events) if (c == '\n') ++lineCount; + std::cout << "Read " << lineCount << " ANSLogger error event(s), " + << events.size() << " bytes total" << std::endl; + + // ── 2. Iterate line-by-line: extract timestamp + message ──────────────── + // Format is ": " — split on the first ": ". + // Prints the most recent 5 events so output isn't overwhelming. + std::cout << "\n--- last 5 events (timestamp / message) ---" << std::endl; + std::vector> parsed; + parsed.reserve(static_cast(lineCount)); + size_t lineStart = 0; + for (size_t i = 0; i < events.size(); ++i) { + if (events[i] != '\n') continue; + std::string line = events.substr(lineStart, i - lineStart); + lineStart = i + 1; + auto sep = line.find(": "); + if (sep == std::string::npos) { + parsed.emplace_back(std::string(), std::move(line)); + } else { + parsed.emplace_back(line.substr(0, sep), line.substr(sep + 2)); + } + } + const size_t showFrom = parsed.size() > 5 ? parsed.size() - 5 : 0; + for (size_t i = showFrom; i < parsed.size(); ++i) { + // Truncate noisy messages so the console stays readable. + std::string msg = parsed[i].second; + if (msg.size() > 120) msg = msg.substr(0, 117) + "..."; + std::cout << " [" << parsed[i].first << "] " << msg << std::endl; + } + + // ── 3. C extern entry point (this is what LabVIEW calls) ──────────────── + // Signature: int GetANSLoggerErrorEventsCpp(int clearAfterRead, std::string& out) + // Passing 0 for clearAfterRead = read only. + std::string fromExtern; + int rc = GetANSLoggerErrorEventsCpp(0, fromExtern); + std::cout << "\nGetANSLoggerErrorEventsCpp rc=" << rc + << " bytes=" << fromExtern.size() << std::endl; + + // ── 4. (DANGER) clear the Application channel after reading ───────────── + // Uncomment ONLY if you actually want to wipe every event from every + // source in the Application log (not just ANSLogger). Run as Admin or + // the clear silently fails (the read still succeeds either way). + // + // std::string cleared; + // int rcClear = GetANSLoggerErrorEventsCpp(1 /* clearAfterRead */, cleared); + // std::cout << "After clear: rc=" << rcClear + // << " events returned=" << std::count(cleared.begin(), cleared.end(), '\n') + // << " (next call should report 0)" << std::endl; + + return lineCount; +} + int main() { //ANSLLMOllamaTest(); @@ -434,5 +518,6 @@ int main() // EncrypyionExample(); ScanDevicesTest(); + GetEventLogErrorsTest(); }