Support Get log events

This commit is contained in:
2026-05-24 09:19:24 +10:00
parent 47b80102a8
commit ebba70b9d9
5 changed files with 316 additions and 2 deletions
+165
View File
@@ -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
// ============================================================================