本地计算机上的服务启动然后停止错误

时间:2013-03-25 03:36:14

标签: c# logging windows-services event-log custom-eventlog

我有一个Windows服务。它正常工作,直到我添加代码开始记录。现在,当我尝试启动该服务时,收到以下错误:

  

然后,本地计算机上的GBBService服务已停止。一些   如果他们没有工作要做,服务会自动停止   例如,性能日志和警报服务

以下是我服务的代码: - 来自项目内部安装程序

public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    string eventSource = "GBBServiceLog";

    public ProjectInstaller()
    {
        InitializeComponent();
        EventLogInstaller installer = FindInstaller(this.Installers);
        if (installer != null)
        {
            installer.Source = eventSource;
            installer.Log = "My GBBServiceLog";
        }
    }

    private EventLogInstaller FindInstaller(InstallerCollection installers)
    {
        foreach (Installer installer in installers)
        {
            if (installer is EventLogInstaller)
            {
                return (EventLogInstaller)installer;
            }
            EventLogInstaller eventLogInstaller = FindInstaller(installer.Installers);
            if (eventLogInstaller != null)
                return eventLogInstaller;
        }
        return null;
    }

    protected override void OnCommitted(IDictionary savedState)
    {
        base.OnCommitted(savedState);
        // Start the service after installation
        using (ServiceController sc = new ServiceController(this.serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
}

从我的服务中:

public GBBService()
    {
        InitializeComponent();
        EventLog.Source = eventSource;
        EventLog.Log = "My GBB Service Log";

    }

    protected override void OnStart(string[] args)
    {
        EventLog.WriteEntry("GBBService Service Started");
    }

我的代码中有错误吗?

1 个答案:

答案 0 :(得分:2)

我认为问题是你正在尝试写一个不存在的EventLog

ServiceInstaller中,您可以创建EventLog My GBBServiceLog

if (installer != null)
{
    installer.Source = eventSource;
    installer.Log = "My GBBServiceLog";
}

但在Service中,您尝试写入My GBB Service Log

public GBBService()
{
    InitializeComponent();
    EventLog.Source = eventSource;
    EventLog.Log = "My GBB Service Log"; <--------------
}

我认为应该是:

public GBBService()
{
    InitializeComponent();
    EventLog.Source = eventSource;
    EventLog.Log = "My GBBServiceLog";
}