public static void Log(IService service, object value) { if (!OptionService) { if (OptionLogToConsole) { try { if (service != null && service.Name != null) { Console.WriteLine("[" + Thread.CurrentThread.ManagedThreadId + "][" + service.Name + "]: " + value); } else { Console.WriteLine("[" + Thread.CurrentThread.ManagedThreadId + "]: " + value); } } catch { ConsoleControl.AllocConsole(); try { if (service != null && service.Name != null) { Console.WriteLine("[" + Thread.CurrentThread.ManagedThreadId + "][" + service.Name + "]: " + value); } else { Console.WriteLine("[" + Thread.CurrentThread.ManagedThreadId + "]: " + value); } } catch { // do nothing } } } } else { if (service != null && service.Name != null) { Trace.WriteLine(value, service.Name); } else { Trace.WriteLine(value); } } }
static void Main(string[] args) { bool newConsole = ConsoleControl.AllocConsole(); ConsoleControl.SetConsoleIcon(ConsoleControl.ApplicationIcon); // we need that early on (for error reporting) OptionName = CommandLineUtilities.GetArgument <string>(args, "name", DefaultName); OptionEncoding = CommandLineUtilities.GetArgument <Encoding>(args, "encoding", null); if (OptionEncoding != null) { _oldEncoding = Console.OutputEncoding; Console.WriteLine("Switching output encoding from '" + _oldEncoding.WebName + "' to '" + OptionEncoding.WebName + "'"); Console.OutputEncoding = OptionEncoding; } _closed = new AutoResetEvent(true); _service = new Program(); _service.AutoLog = false; _service.EventLog.Source = OptionName; SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException; try { SafeMain(args); } catch (Exception e) { bool reported = false; if (_service != null) { try { _service.EventLog.WriteEntry("Service Host '" + OptionName + "' was stopped due to an error: " + e, EventLogEntryType.Error); reported = true; } catch { } } if (!reported) { EventLog.WriteEntry(OptionName, "Service Host '" + OptionName + "' was stopped due to an error: " + e, EventLogEntryType.Error); } EventLog.WriteEntry(OptionName, "Service Host '" + OptionName + "' was stopped due to an error: " + e, EventLogEntryType.Error); Log("Fatal error. Details:"); Log(e); } if (_oldEncoding != null) { Console.OutputEncoding = _oldEncoding; } if (newConsole) { ConsoleControl.FreeConsole(); } ConsoleControl.SetConsoleIcon(0); }