C#实现自定义windows系统日志的方法
程序员文章站
2023-01-10 16:46:33
本文实例讲述了c#实现自定义windows系统日志的方法。分享给大家供大家参考。具体实现方法如下:
using system;
using system.col...
本文实例讲述了c#实现自定义windows系统日志的方法。分享给大家供大家参考。具体实现方法如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.diagnostics; namespace consoleapp { /// <summary> /// 系统日志 /// </summary> public class packsystemeventlog { /// <summary> /// 错误信息 /// </summary> private static string errorinfo { get; set; } /// <summary> /// 创建系统事件日志分类 /// </summary> /// <param name="eventsourcename">注册事件源(比如说这个日志来源于某一个应用程序)</param> /// <param name="logname">日志名称(事件列表显示的名称)</param> /// <returns></returns> public static bool createsystemeventlogcategory(string eventsourcename, string logname) { bool createresult = false; try { if (!eventlog.sourceexists(eventsourcename)) { eventlog.createeventsource(eventsourcename, logname); } createresult = true; } catch (exception ex) { createresult = false; errorinfo = ex.message; } return createresult; } /// <summary> /// 删除系统事件日志分类 /// </summary> /// <param name="eventsource">eventname事件源</param> /// <returns></returns> public static bool removesystemeventsourcecategory(string eventsource) { bool createresult = false; try { if (eventlog.sourceexists(eventsource)) { eventlog.deleteeventsource(eventsource, "."); } createresult = true; } catch (exception ex) { createresult = false; errorinfo = ex.message; } return createresult; } /// <summary> /// 向系统日志中写入日志 /// </summary> /// <param name="eventsource">事件源</param> /// <param name="msg">写入日志信息</param> /// <param name="type">日志文本分类(警告、信息、错误)</param> /// <returns></returns> public static bool writesystemeventlog(string eventsource, string msg, eventlogentrytype type) { bool writeresult = false; try { if (!eventlog.sourceexists(eventsource)) { writeresult = false; errorinfo = "日志分类不存在!"; } else { eventlog.writeentry(eventsource, msg, type); writeresult = true; } } catch (exception ex) { writeresult = false; errorinfo = ex.message; } return writeresult; } /// <summary> /// 删除事件源中logname(好像删除了所有的该分类的日志) /// </summary> /// <param name="eventsource"></param> /// <param name="logname"></param> /// <returns></returns> public static bool removesystemeventlog(string eventsource, string logname) { bool removeresult = false; try { if (!eventlog.sourceexists(eventsource)) { removeresult = false; errorinfo = "日志分类不存在!"; } else { eventlog.delete(logname); removeresult = true; } } catch (exception ex) { removeresult = false; errorinfo = ex.message; } return removeresult; } /// <summary> /// 获取错误信息 /// </summary> /// <returns></returns> public static string geterrormessage() { return errorinfo; } } }
希望本文所述对大家的c#程序设计有所帮助。
下一篇: C#实现实体类与字符串互相转换的方法