小编给大家分享一下如何使用C#实现写入系统日志,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
站在用户的角度思考问题,与客户深入沟通,找到黄骅网站设计与黄骅网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站设计、成都网站建设、企业官网、英文网站、手机端网站、网站推广、国际域名空间、虚拟空间、企业邮箱。业务覆盖黄骅地区。
因为我不想使用自己写文件,我的软件是绿色的,所以把日志写到 Windows 日志。
首先告诉大家什么是系统日志,请看下面

如果需要写日志,需要管理员权限,如果没有权限会出现下面异常
System.Security.SecurityException:“未找到源,但未能搜索某些或全部事件日志。 不可访问的日志: Security
需要判断当前是否已经存在日志,下面我来创建一个事件叫 “德熙”
if (EventLog.SourceExists("德熙"))
{
EventLog.CreateEventSource("德熙", "Application");
}这里的 Application 就是写到哪个,一般都是选 Application ,可以从图片看到系统的有应用程序、安全、Setup、系统几个日志,程序一般都是写到程序
写日志
写日志就不用管理权限
写入可以使用 WriteEntry ,需要传入写入的日志和内容
EventLog.WriteEntry("德熙", "有个不愿告诉你名称的程序在这里写字符串");这个方法还有几个重载,可以传入日志类型,是成功、失败还是其他。还可以传入 id ,通过id 可以找到为什么需要写日志,不过需要在自己定义,还可以添加附件,于是我就不需要自己写文件日志。
另外给大家附上一个完整例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApp
{
///
/// 系统日志
///
public class PackSystemEventLog
{
///
/// 错误信息
///
private static string ErrorInfo { get; set; }
///
/// 创建系统事件日志分类
///
/// 注册事件源(比如说这个日志来源于某一个应用程序)
/// 日志名称(事件列表显示的名称)
///
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;
}
///
/// 删除系统事件日志分类
///
/// EventName事件源
///
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;
}
///
/// 向系统日志中写入日志
///
/// 事件源
/// 写入日志信息
/// 日志文本分类(警告、信息、错误)
///
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;
}
///
/// 删除事件源中logName(好像删除了所有的该分类的日志)
///
///
///
///
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;
}
///
/// 获取错误信息
///
///
public static string GetErrorMessage()
{
return ErrorInfo;
}
}
}以上是“如何使用C#实现写入系统日志”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
网站栏目:如何使用C#实现写入系统日志
文章URL:http://www.jxjierui.cn/article/phojpd.html


咨询
建站咨询
