如何使用C#创建自定义事件日志

时间:2012-01-06 06:08:29

标签: c# .net windows-services event-log

我创建了一个Windows服务。我创建了一个事件日志。

public Service1()
{
        InitializeComponent();
        this.ServiceName = ConfigurationManager.AppSettings.Get("ServiceName");

        string sourceName = ConfigurationManager.AppSettings.Get("ServiceName");
        string logName = ConfigurationManager.AppSettings["EventLogName"];
        try
        {
            if (!System.Diagnostics.EventLog.Exists(sourceName))
                System.Diagnostics.EventLog.CreateEventSource(sourceName, logName);
            eventLog.Source = sourceName;
            eventLog.Log = logName;
        }
        catch
        {
            eventLog.Source = "Application";
        }
    }

在初始化期间,安装了服务并且未创建日志。日志条目位于系统的Application日志中。

我错过了什么?

我使用了流程安装程序来安装

 public ProjectInstaller()
 {
        InitializeComponent();
        this.Installers.Add(GetServiceInstaller());
        this.Installers.Add(GetServiceProcessInstaller());
 }

 private ServiceInstaller GetServiceInstaller()
 {
        serviceInstaller.ServiceName = GetConfigurationValue("ServiceName");
        serviceInstaller.Description = GetConfigurationValue("Description");
        serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
        return serviceInstaller;
 }

 private ServiceProcessInstaller GetServiceProcessInstaller()
 {
        serviceProcessinstaller.Account = ServiceAccount.LocalSystem;
        return serviceProcessinstaller;
 }

如何创建事件日志?

3 个答案:

答案 0 :(得分:3)

将您的代码更改为以下内容:

    if (!System.Diagnostics.EventLog.SourceExists(sourceName))
            System.Diagnostics.EventLog.CreateEventSource(sourceName, logName);

答案 1 :(得分:0)

首先尝试将AutoLog设置为false。

    this.AutoLog = false;

    if (!System.Diagnostics.EventLog.SourceExists(sourceName)) 
    {        
        System.Diagnostics.EventLog.CreateEventSource(sourceName, logName);
    }

    eventLog.Source = "MySource";

在此MSDN walkthrough中,他们似乎完全省略了该步骤。但是,在此MSDN" How to:"他们说:

  

如果要写入应用程序日志以外的事件日志,则必须将AutoLog属性设置为false,在服务代码中创建自己的自定义事件日志,并将服务注册为有效的条目源。日志中。

将AutoLog设置为false后,我的自定义日志和事件显示为预期。

答案 2 :(得分:0)

ServiceName和Source必须是不同的名称。

<强>的ServiceName

this.serviceInstaller1.ServiceName = "MaliyeWMService";

<强>来源

if (!System.Diagnostics.EventLog.SourceExists("MaliyeMailService"))
{
  System.Diagnostics.EventLog.CreateEventSource("MaliyeMailService", "MaliyeMailServiceLog");

}
OlayLog.Source = "MaliyeMailService";
相关问题