@logtape/windows-eventlog
Version:
Windows Event Log sink for LogTape
102 lines (100 loc) • 3.03 kB
JavaScript
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
const bun_ffi = require_rolldown_runtime.__toESM(require("bun:ffi"));
//#region ffi.bun.ts
/**
* Bun FFI implementation for Windows Event Log API
*/
var WindowsEventLogFFI = class {
eventSource = null;
lib = null;
sourceName;
initialized = false;
metaLogger = (0, __logtape_logtape.getLogger)([
"logtape",
"meta",
"windows-eventlog"
]);
constructor(sourceName) {
this.sourceName = sourceName;
}
/**
* Initialize the FFI bindings and register event source
*/
initialize() {
if (this.initialized) return;
try {
this.lib = (0, bun_ffi.dlopen)("advapi32.dll", {
RegisterEventSourceA: {
args: [bun_ffi.FFIType.ptr, bun_ffi.FFIType.cstring],
returns: bun_ffi.FFIType.ptr
},
ReportEventA: {
args: [
bun_ffi.FFIType.ptr,
bun_ffi.FFIType.u16,
bun_ffi.FFIType.u16,
bun_ffi.FFIType.u32,
bun_ffi.FFIType.ptr,
bun_ffi.FFIType.u16,
bun_ffi.FFIType.u32,
bun_ffi.FFIType.ptr,
bun_ffi.FFIType.ptr
],
returns: bun_ffi.FFIType.bool
},
DeregisterEventSource: {
args: [bun_ffi.FFIType.ptr],
returns: bun_ffi.FFIType.bool
}
});
const encoder = new TextEncoder();
const sourceNameBuffer = encoder.encode(this.sourceName + "\0");
const result = this.lib.symbols.RegisterEventSourceA(null, sourceNameBuffer);
this.eventSource = typeof result === "number" ? result : null;
if (!this.eventSource || this.eventSource === 0) throw new Error(`Failed to register event source: ${this.sourceName}`);
this.initialized = true;
} catch (error) {
throw new Error(`Failed to initialize Windows Event Log FFI: ${error}`);
}
}
/**
* Write an event to Windows Event Log
*/
writeEvent(eventType, eventId, message) {
if (!this.initialized || !this.eventSource || !this.lib) return;
try {
const encoder = new TextEncoder();
const messageBuffer = encoder.encode(message + "\0");
const ptrArray = new BigUint64Array(2);
ptrArray[0] = BigInt((0, bun_ffi.ptr)(messageBuffer));
ptrArray[1] = 0n;
const success = this.lib.symbols.ReportEventA(this.eventSource, eventType, 0, eventId, null, 1, 0, ptrArray, null);
if (!success) throw new Error(`ReportEventA returned false`);
} catch (error) {
throw error;
}
}
/**
* Clean up resources
*/
dispose() {
if (this.initialized && this.eventSource && this.lib) {
try {
this.lib.symbols.DeregisterEventSource(this.eventSource);
} catch (error) {
this.metaLogger.error("Failed to deregister event source during cleanup: {error}", { error });
}
this.eventSource = null;
this.initialized = false;
try {
this.lib.close();
} catch (error) {
this.metaLogger.error("Failed to close FFI library during cleanup: {error}", { error });
}
this.lib = null;
}
}
};
//#endregion
exports.WindowsEventLogFFI = WindowsEventLogFFI;