Support Get log events
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
#include "ANSUtilities.h"
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#include <winevt.h> // EvtQuery / EvtRender for GetANSLoggerErrorEvents
|
||||
#pragma comment(lib, "wevtapi.lib")
|
||||
#endif
|
||||
#include <iostream>
|
||||
#include <CkFileAccess.h>
|
||||
@@ -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 <EventData><Data>...</Data></EventData>.
|
||||
//
|
||||
// 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<wchar_t> 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<DWORD>(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<DWORD>(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 <Data>...</Data> inside <EventData> ----
|
||||
// ReportEventW with N strings produces N consecutive <Data>
|
||||
// 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"<EventData");
|
||||
auto edEnd = xml.find(L"</EventData>", edStart);
|
||||
if (edStart != std::wstring::npos && edEnd != std::wstring::npos) {
|
||||
auto bodyEnd = edEnd;
|
||||
auto cursor = edStart;
|
||||
while (cursor < bodyEnd) {
|
||||
auto dOpen = xml.find(L"<Data", cursor);
|
||||
if (dOpen == std::wstring::npos || dOpen >= bodyEnd) break;
|
||||
auto dGt = xml.find(L'>', dOpen);
|
||||
if (dGt == std::wstring::npos || dGt >= bodyEnd) break;
|
||||
auto dClose = xml.find(L"</Data>", 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("</Data>") - 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
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -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
|
||||
// "<DD/MM/YYYY h:mm:ss tt>: <event data string>\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:
|
||||
// "<DD/MM/YYYY h:mm:ss tt>: <event data>\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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<int>(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; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user