C#实现自定义windows系统日志的方法
本文实例讲述了C#实现自定义windows系统日志的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Diagnostics; namespaceConsoleApp { ///<summary> ///系统日志 ///</summary> publicclassPackSystemEventLog { ///<summary> ///错误信息 ///</summary> privatestaticstringErrorInfo{get;set;} ///<summary> ///创建系统事件日志分类 ///</summary> ///<paramname="eventSourceName">注册事件源(比如说这个日志来源于某一个应用程序)</param> ///<paramname="logName">日志名称(事件列表显示的名称)</param> ///<returns></returns> publicstaticboolCreateSystemEventLogCategory(stringeventSourceName,stringlogName) { boolcreateResult=false; try { if(!EventLog.SourceExists(eventSourceName)) { EventLog.CreateEventSource(eventSourceName,logName); } createResult=true; } catch(Exceptionex) { createResult=false; ErrorInfo=ex.Message; } returncreateResult; } ///<summary> ///删除系统事件日志分类 ///</summary> ///<paramname="eventSource">EventName事件源</param> ///<returns></returns> publicstaticboolRemoveSystemEventSourceCategory(stringeventSource) { boolcreateResult=false; try { if(EventLog.SourceExists(eventSource)) { EventLog.DeleteEventSource(eventSource,"."); } createResult=true; } catch(Exceptionex) { createResult=false; ErrorInfo=ex.Message; } returncreateResult; } ///<summary> ///向系统日志中写入日志 ///</summary> ///<paramname="eventSource">事件源</param> ///<paramname="msg">写入日志信息</param> ///<paramname="type">日志文本分类(警告、信息、错误)</param> ///<returns></returns> publicstaticboolWriteSystemEventLog(stringeventSource,stringmsg,EventLogEntryTypetype) { boolwriteResult=false; try { if(!EventLog.SourceExists(eventSource)) { writeResult=false; ErrorInfo="日志分类不存在!"; } else { EventLog.WriteEntry(eventSource,msg,type); writeResult=true; } } catch(Exceptionex) { writeResult=false; ErrorInfo=ex.Message; } returnwriteResult; } ///<summary> ///删除事件源中logName(好像删除了所有的该分类的日志) ///</summary> ///<paramname="eventSource"></param> ///<paramname="logName"></param> ///<returns></returns> publicstaticboolRemoveSystemEventLog(stringeventSource,stringlogName) { boolremoveResult=false; try { if(!EventLog.SourceExists(eventSource)) { removeResult=false; ErrorInfo="日志分类不存在!"; } else { EventLog.Delete(logName); removeResult=true; } } catch(Exceptionex) { removeResult=false; ErrorInfo=ex.Message; } returnremoveResult; } ///<summary> ///获取错误信息 ///</summary> ///<returns></returns> publicstaticstringGetErrorMessage() { returnErrorInfo; } } }
希望本文所述对大家的C#程序设计有所帮助。