如何使用 C# 创建自定义事件日志 [英] How to create a custom event log using C#

查看:42
本文介绍了如何使用 C# 创建自定义事件日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a Windows service. I create an event log.

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 日志中.

During initialization, the service is installed and log is not created. The log entries are in the Application log of the system.

我错过了什么?

我使用进程安装程序来安装

I used process installer to installation

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

如何创建事件日志?

推荐答案

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

change your code to following:

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

请注意 根据 Microsoft 的 KB,事件日志名称的前 8 个字符必须与计算机上的所有其他事件日志不同(因此,如果用户的计算机已经有名为 的日志);Application" 那么你不能创建一个名为 Applicat1"ApplicationFoobar" 的新 EventLog 因为它们共享相同的8 个字符作为内置 Application 事件日志).

Note that as per Microsoft's KB, the first 8 characters of the Event Log name must be distinct from all other Event Logs on the computer (so if the user's computer already has a log named "Application" then you cannot create a new EventLog named "Applicat1" or "ApplicationFoobar" as they share the same 8 characters as the built-in Application event-log).

这篇关于如何使用 C# 创建自定义事件日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆