0

I have a windows service installed, it is running.

I have a write to event log entry, when the system is shutdown, however the code doesn't write to event log on system shut down or restart.

protected override void OnShutdown()   
{  
    WriteToEventLog("Services shut down.");       
}

private void WriteToEventLog(string logMessage)
{
    var mySource = "MySourceLog";
    // Create the source and log, if it does not already exist.
    if (!EventLog.SourceExists(mySource))
    {
        EventLog.CreateEventSource(mySource, mySource); 
    }
    // Create an EventLog instance and assign its source.
    using (var eventLog = new EventLog())
    {
        eventLog.Source = mySource;
        // Write an entry to the event log.
        eventLog.WriteEntry(logMessage, EventLogEntryType.Warning, 1002);
    }
}

I want to write an event into event log whenever my windows service crashes and possibly send an email as an alert saying the service crashed. How can i detect that service has been crashed and write it to event log?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Sharpeye500
  • 8,775
  • 25
  • 95
  • 143
  • 1
    A "crash" usually means "abrupt process termination", no? `OnShutdown` is only called when the service is to be *gracefully* stopped.. – user2864740 May 14 '18 at 23:48
  • 1
    What do you mean by "crashed"? You could wrap your main entry point in a `try/catch` block that writes any unhandled exceptions to the event log. – Rufus L May 14 '18 at 23:48
  • I gracefully stopped, still, it didn't call onshutdown method code. – Sharpeye500 May 14 '18 at 23:50
  • @Rufus L - please write that as an answer, thanks. – Sharpeye500 May 14 '18 at 23:56
  • My suggestion is already documented here, I think: [How can I set up .NET UnhandledException handling in a Windows service?](https://stackoverflow.com/questions/2456819/how-can-i-set-up-net-unhandledexception-handling-in-a-windows-service) – Rufus L May 15 '18 at 00:07

0 Answers0