views:

58

answers:

2

I have a .NET service, based on ServiceBase:

public partial class Service : ServiceBase

Something initiates stop on this service. The stuff logged during service stop is consistent with a regular stop using SCM, but user states he didn't initiate it. I am not sure if that is some sort of crash, or user error.

Since the OnStop method is getting invoked, I would like to log some diagnostic information in order to see what caused the stop to occur. Is it possible to get this information at that point? I'm looking: what was user that initiated stop, from which workstation/ip address was it initiated, that sort of stuff. Any ideas?

+1  A: 

In the system event log on the machine running the service there should be an event for when the service is shut down. The details of the event will list the user that initiated the stop request.

You can access the eventlog through code, however I'm not sure if you can capture the event info tied to shutting down the service in its OnStop method. Here's some code you might be able to adapt for your situation if you want to try -

       foreach (EventLog logs in System.Diagnostics.EventLog.GetEventLogs())
       {
            if (logs.LogDisplayName.ToUpper() == "SYSTEM")
            {
                foreach (EventLogEntry logEntry in logs.Entries)
                {
                    if(logEntry.TimeGenerated >= DateTime.Now.AddMinutes(-2))
                    {
                        Console.WriteLine("User: {0} Message: {1}", logEntry.UserName, logEntry.Message);
                    }
                }
            }
        }
kragan
Nope. Mine has event id 7036, which says "The XXXXXX service entered the stopped state". User is "N/A". What I was looking for was more - how to query such information programmatically, inside OnStop() function
galets
I usually see event id 7035 preceding the 7036. 7035 includes the user and should be like - "The XXXXX service was successfully sent a stop control."
kragan
A: 

All, the issue was: an exception thrown in a destructor of one class. Apparently, it is not possible to intercept such an event. Thanks everyone for taking time on this issue.

This thread can shed some light on destructor issue

galets