How could I log that a Windows service is terminating because of a system shutdown?
I have a diagnostic version of a s开发者_运维问答ervice that logs as much as possible in the OnStart() and OnStop() methods.
One event that I am unable to capture is when the computer is physically restarted. My logging function usually records its output to a table in a database, but when that is not available it posts to the EventLog.
On a reboot my service neither logs to the table nor to the EventLog.
It makes sense to me that I would not be able to post to the table, since SQL Server is in the process of shutting down, but it also seems that due to a timing issue the EventLog may also be shutting before the service can default to write there.
In the case of a shutdown, MSSQLSERVER reports an information message in the EventLog:
SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.
Is there a way to do something similar for my service?
You can specify the dependencies of your Windows Service to have it require another service. If you specify a dependency on the EventLog service, then Windows will wait until your service is shut down before shutting down the Event Log.
http://kb2.adobe.com/cps/400/kb400960.html describes how to do it by modifying a few registry keys.
Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and locate the service that you need to set a dependency for. Open the 'DependOnService' key on the right side. If the selected service does not have a 'DependOnService' key, then create one by right-clicking and selecting New > Multi-String Value. In the value field, enter the names of all services that the current service will depend on. Each service name must be entered properly and on a separate line.
There is an OnShutdown method your can override in your service. It will be called when the machine is shutting down. Write to the event log from that method, then call base.OnShutdown().
Capture SystemEvents.SessionEnding
On the OnStart you could capture it and handle
like
Microsoft.Win32.SystemEvents.SessionEnding += new Microsoft.Win32.SessionEndingEventHandler(this.zomgRebootinglol);
You can capture windows events by using the SystemEvents-Class.
Also take a look at the events. I think the Event you are looking for is: SystemEvents::PowerModeChanged Event and/or SystemEvents::SessionEnded
精彩评论