如何在.NET中引发事件查看器“事件”?

时间:2009-06-23 09:44:04

标签: c# .net

我想在.NET中引发一个出现在系统事件查看器(eventvwr.exe)中的“事件”。

不幸的是,谷歌只是给了我很多关于“事件”的东西,这些事件不是我想提出的事件。

什么是正确的API调用?

更新 谢谢你到目前为止的答案。有趣的是,我发现即使我没有创建源,对“LogEvent”的调用也可以使用新的源代码。即。

// The following works even though I haven't created "SomeNewSource"
EventLog.WriteEntry("SomeNewSource", message);

任何人都可以解释为什么会这样吗?

4 个答案:

答案 0 :(得分:5)

using System;
using System.Diagnostics;

namespace Test
{
    class TestEventLog
    {
        static void Main(string[] args)
        {
            string source = "MyApplication";

            if (!EventLog.SourceExists(source))
            {
                EventLog.CreateEventSource(source,"Application");
            }

            EventLog.WriteEntry(source, "Here is an event-log message");
        }
    }
}

答案 1 :(得分:2)

如果源尚不存在,则调用CreateEventSource,然后使用WriteEntry写入日志。但是,有几件事要记住。

CreateEventSource将在程序第一次运行时需要管理员访问权限。我总是只保留一个简短的命令行程序,将事件源作为参数。在安装期间仅以管理员身份运行一次,然后您的程序可以在适当的访问级别下编写没有问题的事件。

WriteEntry还采用条目类型和错误号,如:

myEventLog.WriteEntry("Health Check. Program started normally",EventLogEntryType.Info,1011);

myEventLog.WriteEntry("Error. Could not open database connection!",EventLogEntryType.Error,1012);

这些可能会有所帮助,因为可以将Microsoft Operations Manager等监视系统设置为观看这些系统并通知您或通话中的人员。我通常会创建一组唯一的错误号,以便系统管理员知道应该打电话给谁;我,dba,供应商的帮助热线,以报告他们的Web服务,等等。为您节省大量的2AM电话。

以下是一个示例:

using System.Diagnostics;
class TestClass
{
    private EventLog log;

    public TestClass()
    {
        if(!EventLog.SourceExists("TestApplication"))
        {
            EventLog.CreateEventSource("TestApplication","Application");
        }
        log=new EventLog("Application",".","TestApplication");
    }

    public int ParseFile(StreamReader sr)
    {
        string[] lines=sr.ReadToEnd().Trim().Split('\n');
        int linecount=lines.Length;
        string connString=System.Configuration.ConfigurationSettings.AppSettings["ConnectString"];
        SqlConnection conn=new SqlConnection(connString);
        try
        {
            conn.Open();
        }
        catch (Exception e)
        {
            log.WriteEntry("Cannot connect to database for file import: "+e.Message, EventLogEntryType.Error,1171);
            return linecount;
        }
        // write to database, etc.
    }
}

答案 2 :(得分:1)

答案 3 :(得分:1)