做一件安装一个Windows服务时,需要手动创建一个Windows事件日志源创建一个、事件、日志、Windows

2023-09-03 06:42:55 作者:舔狗

我公司开发的Windows服务在C#。我创建了一个安装使用Visual Studio 2008中,将安装Windows服务。一切都已经很不错了。我想,以确保该事件源已被创建在安装时,让所有的错误/异常情况,在运行时被正确记录到Windows事件日志。

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

 保护覆盖无效OnBeforeInstall(IDictionary的savedState)
{
    base.OnBeforeInstall(savedState);

    如果(!EventLog.SourceExists(服务名称))
        EventLog.CreateEventSource(服务名称,应用程序);
}

保护覆盖无效OnAfterUninstall(IDictionary的savedState)
{
    base.OnAfterInstall(savedState);

    如果(EventLog.SourceExists(服务名称))
        EventLog.DeleteEventSource(服务名称);
}
 

解决方案

在我看来,像的ServiceInstaller 自动安装具有相同的名称作为服务过程中创建一个数据源,所以没有必要进行任何额外的code。

在ServiceInstaller文档

  

在执行安装时,它会自动创建一个EventLogInstaller安装与ServiceBase的派生类关联的事件日志源。日志属性这个源由的ServiceInstaller构造计算机的应用程序日志设置。当您设置的ServiceInstaller(这应该是相同的ServiceBase的的服务.. ::。服务名称)的服务名称,信号源自动设置为相同的值。在安装失败,源的安装回滚以及previously安装服务。

不再手动切换,用这个小工具一键开启 Windows 夜间模式

I have developed a Windows service in C#. I have created a installer with Visual Studio 2008, which installs the Windows service. Everything is good so far. I want to make sure that the event source has been created at install time, so that any error/exception conditions at runtime are correctly logged to the Windows event log.

Does the event source get automatically created (and removed) as part of the windows service installation (and uninstallation), or do I have to handle this myself and create a custom action to create and delete it as follows?

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);
}

解决方案

It appears to me like the ServiceInstaller automatically creates a DataSource during installation with the same name as the service, so there's no need for any extra code.

From the ServiceInstaller documentation

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.