@logtape/windows-eventlog
Version:
Windows Event Log sink for LogTape
84 lines (82 loc) • 2.52 kB
JavaScript
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
const require_types = require('./types.cjs');
const require_formatter = require('./formatter.cjs');
const require_platform = require('./platform.cjs');
const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
//#region src/sink.ts
/**
* Helper function to remove any trailing newline that the formatter may add
* to the string. When writing to the event log, we don't want newlines at the
* end of the message.
*/
function stripTrailingNewline(s) {
if (s.length > 0 && s.at(s.length - 1) === "\n") return s.substring(0, s.length - 1);
else return s;
}
/**
* Creates a Windows Event Log sink, parameterized on the FFI implementation.
*
* @param {WindowsEventLogFFI} ffi Actual FFI implementation to use
* @param options Configuration options for the sink
* @returns A LogTape sink that writes to Windows Event Log
* @throws {WindowsPlatformError} If not running on Windows
* @throws {WindowsEventLogError} If Event Log operations fail
*
* @example
* ```typescript
* import { getWindowsEventLogSink } from "@logtape/windows-eventlog";
*
* const sink = getWindowsEventLogSink({
* sourceName: "MyApp"
* });
* ```
*
* @since 1.0.0
*/
function getWindowsEventLogSinkForFFI(ffi, options) {
require_platform.validateWindowsPlatform();
const { sourceName, eventIdMapping = {} } = options;
const eventIds = {
...require_types.DEFAULT_EVENT_ID_MAPPING,
...eventIdMapping
};
const metaLogger = (0, __logtape_logtape.getLogger)([
"logtape",
"meta",
"windows-eventlog"
]);
const sink = (record) => {
try {
ffi.initialize(sourceName);
} catch (error) {
metaLogger.error("Failed to initialize Windows Event Log FFI: {error}", { error });
return;
}
const eventType = require_types.mapLogLevelToEventType(record.level);
const eventId = eventIds[record.level];
const formatter = options.formatter ?? require_formatter.defaultWindowsEventlogFormatter;
const fullMessage = stripTrailingNewline(formatter(record));
const parameters = eventId === require_types.NELOG_OEM_Code ? [
fullMessage,
"",
"",
"",
"",
"",
"",
"",
""
] : [fullMessage];
try {
ffi.writeEvent(eventType, eventId, parameters);
} catch (error) {
metaLogger.error("Failed to write to Windows Event Log: {error}", { error });
}
};
sink[Symbol.dispose] = () => {
ffi.dispose();
};
return sink;
}
//#endregion
exports.getWindowsEventLogSinkForFFI = getWindowsEventLogSinkForFFI;