using System.Runtime.Versioning; using static Chronos.Server.Hosting.Windows.ServiceNative; namespace Chronos.Server.Hosting.Windows; /// /// Errors of the Windows service in the Application event log (source ChronosServer). A service has no console, /// and a start-up failure comes before the server's log file exists (the data folder that holds it may be the very /// thing refused), so Event Viewer is where an operator finds why the service stopped. The source is not registered /// with a message file: Event Viewer says it found no description for the event, then shows the text whole. /// internal static unsafe class ServiceEventLog { public const uint StartFailed = 1; public const uint StopFailed = 2; /// ReportEvent takes at most 31,839 characters per string. public const int MaxLength = 31_839; /// /// The event text: and the reason the server gave (the entry to check, for a refused data /// folder), then the exception for a bug report; cut to . /// public static string Describe(string what, Exception exception) { var text = $"{what} {exception.Message}{Environment.NewLine}{Environment.NewLine}{exception}"; if (text.Length <= MaxLength) return text; var cut = MaxLength - 1; // Never half a surrogate pair. if (char.IsHighSurrogate(text[cut - 1])) cut--; return string.Concat(text.AsSpan(0, cut), "…"); } /// Writes an error event; false when the event log could not be written (the console still gets it). [SupportedOSPlatform("windows")] public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text); /// as (tests write as their own source). [SupportedOSPlatform("windows")] internal static bool Error(string sourceName, uint eventId, string text) { var source = RegisterEventSourceW(null, sourceName); if (source == 0) return false; try { fixed (char* chars = text.Length <= MaxLength ? text : text[..MaxLength]) { var strings = stackalloc char*[1]; strings[0] = chars; return ReportEventW(source, EventLogErrorType, 0, eventId, 0, 1, 0, strings, null); } } finally { DeregisterEventSource(source); } } }