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

Poo*_*oja 4 .net c# 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";
        }
    }
Run Code Online (Sandbox Code Playgroud)

初始化期间,会安装服务但不会创建日志。日志条目位于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;
 }
Run Code Online (Sandbox Code Playgroud)

如何创建事件日志?

Afs*_*hin 6

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

if (!System.Diagnostics.EventLog.SourceExists(source: sourceName))
{
    System.Diagnostics.EventLog.CreateEventSource(source: sourceName, logName: logName);
}
Run Code Online (Sandbox Code Playgroud)

请注意,根据 Microsoft 的 KB,事件日志名称的前 8 个字符必须与计算机上的所有其他事件日志不同(因此,如果用户的计算机已有一个名为的日志,"Application"则您无法创建新的EventLog命名日志"Applicat1",或者"ApplicationFoobar"因为它们共享该日志)与内置Application事件日志相同的 8 个字符)。

  • 我试过你的代码。但它没有创建事件日志并且无法启动服务。服务显示服务无法启动。System.ArgumentException:源“SyncronizationService”未在日志“SyncronizationLog”中注册。(它注册在日志'Application'中。) " Source 和 Log 属性必须匹配,或者您可以将 Log 设置为空字符串,它会自动与 Source 属性匹配。错误消息 (2认同)
  • 请注意,logName 必须具有唯一的第一个字符,请检查此链接http://msdn.microsoft.com/en-us/library/y7x55536%28v=vs.90%29.aspx (2认同)