zoukankan      html  css  js  c++  java
  • EventLog 类【转】

    EventLog 类提供了C#与Windows事件日志交互的功能。  很多时候我们可以把日志写到windows事件日志中.

    说明:EventLog 使您可以访问或自定义Windows 事件日志。通过C#提供的EventLog类,可以读取现有日志,向日志中写入项,创建或删除事件源,删除日志,以及响应日志项。也可在创建事件源时创建新日志。

    打开Windows事件日志的方法

    右击我的电脑->管理->事件日志就可以了.

    CreateEventSource
    已重载。 建立一个能够将事件信息写入到系统的特定日志中的应用程序。


    Delete
    已重载。 移除日志资源。


    DeleteEventSource
    已重载。 从事件日志中移除应用程序的事件源注册。

    SourceExist
    已重载。 在计算机的注册表中搜索给定的事件源。


    WriteEntry
    已重载。 将项写入事件日志。


    WriteEvent
    已重载。 向事件日志写入本地化事件项。

    为了能够使用EventLog,我们需要引入usingSystem.Diagnostics命令空间.下面两个方法在你捕获到异常或其他时可以调用.

    private void WriteError(string sText)
    {
         if (!EventLog.SourceExists(sEventSource))
                 EventLog.CreateEventSource(sEventSource, sEventLog);
              EventLog.WriteEntry(sEventSource,sText, EventLogEntryType.Error);

    }

    private void WriteInfo(string sText)
    {
           if (!EventLog.SourceExists(sEventSource))
               EventLog.CreateEventSource(sEventSource, sEventLog);
            EventLog.WriteEntry(sEventSource,sText, EventLogEntryType.Information);       
    }

     

    下面是一个简单使用的例子.

    try

    {

    if(1/0);

    }

    catch(Excepetion ex)

    {

    WriteError(ex.message);

    }

    这样我们就可以成功的写入到Windows事件中..:)

    EventLog(事件日志)的读写方法

    在C#中读写EventLog(事件日志)挺简单的,代码量也比较小。

    1.加入System.DiagnosticsName Space;

    using System.Diagnostics;

    2.声明一个EventLog类的实例。

    EventLog eventLog;
    eventLog=new EventLog("TestEvent",".","mySource");

    "TestEvent"是建立一个新的EventLog名,
    ".": 表示本机
    "mySource": 源名
    如果以上不设参数,就默认为"Application"

    设好以后,就可以读写了。

    写:

    eventLog.Source="mySource";
    eventLog.WriteEntry("Log text");
    MessageBox.Show("Write Complete!")


    读:

    lstEvent.Items.Clear();
    eventLog.Log="TestEvent";
    foreach(EventLogEntry eventlogEntry in eventLog.Entries)
    {
    lstEvent.Items.Add(eventlogEntry.Message);
    }

     

  • 相关阅读:
    Angular Universal 学习笔记
    SAP Spartacus 如何获得当前渲染页面的 CMS 元数据
    Angular 服务器端渲染的学习笔记(二)
    Angular 服务器端渲染的学习笔记(一)
    第三方外部 Saas提供商如何跟使用 SAP 系统的客户进行对接接口集成
    如何从 SAP Spartacus Product Detail 页面,找到其 Angular 实现 Component 的位置
    具备自动刷新功能的 SAP ABAP ALV 报表
    C++学习目录
    c--条件编译
    c--文件读写--二进制
  • 原文地址:https://www.cnblogs.com/chenqingwei/p/1923912.html
Copyright © 2011-2022 走看看