• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#EventLog

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中操作XMLNode节点细节操作发布时间:2022-07-13
下一篇:
C#关闭进程发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap