如何记录 Windows 服务因系统关闭而终止?
我有一个服务的诊断版本,它在 OnStart() 和 OnStop() 方法中记录尽可能多的信息。
我无法捕获的一个事件是计算机物理重新启动时。我的日志记录功能通常将其输出记录到数据库中的表中,但当该表不可用时,它会发布到事件日志。
重新启动时,我的服务既不记录到表也不记录到事件日志。
对我来说,我无法发布到表中是有道理的,因为 SQL Server 正在关闭过程中,但似乎由于计时问题,EventLog 也可能在服务默认为之前关闭写在那里。
在关闭的情况下,MSSQLSERVER 在事件日志中报告一条信息消息:
由于系统关闭,SQL Server 正在终止。这只是一条信息性消息。无需用户执行任何操作。
有没有办法为我的服务做类似的事情?
I have a diagnostic version of a service 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以指定 Windows 服务的依赖关系以使其需要其他服务。如果您指定对 EventLog 服务的依赖关系,则 Windows 将等到您的服务关闭后再关闭事件日志。
http://kb2.adobe.com/cps/400/kb400960.html 描述如何通过修改几个注册表项来实现此目的。
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.
您可以在服务中重写 OnShutdown 方法。当机器关闭时它将被调用。从该方法写入事件日志,然后调用 base.OnShutdown()。
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().
捕获 SystemEvents.SessionEnding
在 OnStart 上 可以捕获它并
处理
Capture SystemEvents.SessionEnding
On the OnStart you could capture it and handle
like
您可以使用 SystemEvents-Class。
另请查看事件。
我认为您正在寻找的事件是: SystemEvents::PowerModeChanged Event 和/或 SystemEvents::SessionEnded
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