UNPKG

@logtape/windows-eventlog

Version:

Windows Event Log sink for LogTape

84 lines (82 loc) 2.38 kB
import { DEFAULT_EVENT_ID_MAPPING, NELOG_OEM_Code, mapLogLevelToEventType } from "./types.js"; import { defaultWindowsEventlogFormatter } from "./formatter.js"; import { validateWindowsPlatform } from "./platform.js"; import { getLogger } from "@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) { validateWindowsPlatform(); const { sourceName, eventIdMapping = {} } = options; const eventIds = { ...DEFAULT_EVENT_ID_MAPPING, ...eventIdMapping }; const metaLogger = 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 = mapLogLevelToEventType(record.level); const eventId = eventIds[record.level]; const formatter = options.formatter ?? defaultWindowsEventlogFormatter; const fullMessage = stripTrailingNewline(formatter(record)); const parameters = eventId === 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 export { getWindowsEventLogSinkForFFI }; //# sourceMappingURL=sink.js.map