gpt4 book ai didi

c# - 安装Windows服务时是否需要手动创建Windows事件日志源

转载 作者:可可西里 更新时间:2023-11-01 08:19:55 25 4
gpt4 key购买 nike

我用 C# 开发了一个 Windows 服务。我用 Visual Studio 2008 创建了一个安装程序,它安装了 Windows 服务。到目前为止一切都很好。我想确保事件源已在安装时创建,以便运行时的任何错误/异常情况都正确记录到 Windows 事件日志中。

事件源是作为 Windows 服务安装(和卸载)的一部分自动创建(和删除)的,还是我必须自己处理并创建自定义操作来创建和删除它,如下所示?

protected override void OnBeforeInstall(IDictionary savedState)
{
base.OnBeforeInstall(savedState);

if (!EventLog.SourceExists(ServiceName))
EventLog.CreateEventSource(ServiceName, "Application");
}

protected override void OnAfterUninstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);

if (EventLog.SourceExists(ServiceName))
EventLog.DeleteEventSource(ServiceName);
}

最佳答案

在我看来,ServiceInstaller 会在安装期间自动创建一个与服务同名的 DataSource,因此不需要任何额外的代码。

来自ServiceInstaller文档

When the installation is performed, it automatically creates an EventLogInstaller to install the event log source associated with the ServiceBase derived class. The Log property for this source is set by the ServiceInstaller constructor to the computer's Application log. When you set the ServiceName of the ServiceInstaller (which should be identical to the ServiceBase..::.ServiceName of the service), the Source is automatically set to the same value. In an installation failure, the source's installation is rolled-back along with previously installed services.

关于c# - 安装Windows服务时是否需要手动创建Windows事件日志源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1484605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com