代码之家  ›  专栏  ›  技术社区  ›  Paul Hollingsworth

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

  •  1
  • Paul Hollingsworth  · 技术社区  · 16 年前

    我想引发一个“事件”,它从.NET显示在系统事件查看器(eventvwr.exe)中。

    不幸的是,谷歌只是给了我很多关于“事件”的其他东西,而这不是我想要提出的那种事件。

    正确的API调用是什么?

    更新 谢谢你的回答。有趣的是,我发现对“logevent”的调用使用新的源,即使我没有创建源。即

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

    有人能解释这是为什么吗?

    4 回复  |  直到 13 年前
        1
  •  2
  •   R Ubben    16 年前

    如果源不存在,则调用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服务关闭,等等。节省了你凌晨2点的电话。

    这是一个示例:

    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
  •  5
  •   Johnno Nolan    13 年前
    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");
            }
        }
    }
    
        4
  •  1
  •   Joey Gumbo    16 年前