博客
关于我
Log4Net的配置文件以及相应的读写操作类
阅读量:524 次
发布时间:2019-03-08

本文共 5305 字,大约阅读时间需要 17 分钟。

Log4Net C#日志记录开发指南

一、Log4Net基础概述

Log4Net 是一个广泛使用的日志记录框架,为C#开发人员提供强大的日志管理功能。通过Log4Net,开发者可以轻松实现应用程序的日志记录需求,支持文件、数据库、镜像等多种日志存储方式。

二、配置Log4Net

1. 配置文件结构

  • Log4Net.config 最为重要的配置文件。
  • 配置示例代码如下:

2.配置类库引用

在项目中添加log4net.dll参考:

using log4net;using log4net.Appender;using log4net.Config;using log4net.Layout;

三、LogHelper类

1. 类概述

public class LogHelper{  private static ILog log;  public LogHelper(string fileAppenderName)  {    log = LogManager.GetLogger(fileAppenderName);    m_fileAppenderName = fileAppenderName;  }  private string m_fileAppenderName;  public static void LoadLogConfig()  {    XmlConfigurator.Configure(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));  }  public ILog GetLogger()  {    return log;  }  public void WriteLogInfo(string info, string fileFullName = "")  {    if (!string.IsNullOrEmpty(info))    {      log.Info(info);    }  }  public void WriteLogDebug(string info)  {    if (!string.IsNullOrEmpty(info))    {      log.Debug(info);    }  }  /*   // 可以根据具体需求扩展功能,但要注意避免与Log4Net自带的功能冲突  */}

2.使用示例

// 初始化日志记录LogHelper.LoadLogConfig();// 获取特定日志对象ILog errorLog = LogManager.GetLogger(typeof(ErrorHandlingClass));// 写进入日志errorLog.Error("错误信息详细描述:" + exception.Message);

四、LogUtil类

1. 类功能概述

LogUtil 是一个通用日志记录工具,适用于快速实现日志输出功能。

public class LogUtil{  private static readonly LogHelper logHelper = new LogHelper("commonlog");  public static bool WriteDebug(string _message)  {    try    {      logHelper.WriteLogDebug(_message);      return true;    }    catch (Exception ex)    {      Console.WriteLine("Debug: " + ex.Message);      return false;    }  }  public static bool WriteInfo(string _message)  {    try    {      logHelper.WriteLogInfo(_message);      return true;    }    catch (Exception ex)    {      Console.WriteLine("Info: " + ex.Message);      return false;    }  }  public static bool WriteWarn(string _message)  {    try    {      logHelper.WriteLogInfo(_message);      return true;    }    catch (Exception ex)    {      Console.WriteLine("Warn: " + ex.Message);      return false;    }  }  public static bool WriteError(string _message)  {    try    {      logHelper.WriteLogInfo(_message);      return true;    }    catch (Exception ex)    {      Console.WriteLine("Error: " + ex.Message);      return false;    }  }  public static bool WriteFatal(string _message)  {    try    {      logHelper.WriteLogInfo(_message);      return true;    }    catch (Exception ex)    {      Console.WriteLine("Fatal: " + ex.Message);      return false;    }  }}

2. 使用示例

// 调用日志记录方法bool result = LogUtil.WriteDebug("测试调试信息");

五、RecordLogUtil类

1. 类功能概述

RecordLogUtil 是一个结合日志记录与界面显示的工具类,适用于需要同时向数据库或文件记录日志以及在界面展示的场景。

public class RecordLogUtil{  private readonly LogHelper logHelper;  private static readonly event Action
CommonEvent = new Action
((message) =>ificación(message)); private static readonly event Action
CustomEvent = new Action
((message) =>); public RecordLogUtil(string fileAppenderName) { logHelper = new LogHelper(fileAppenderName); } public static void LogToShow(string message, bool toDisplay, bool toWriteLog = true) { if (CommonEvent != null && toDisplay) { CommonEvent(message + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } if (toWriteLog) { LogUtil.WriteDebug(message); } } public static string GetMessageTime(string message) { return $"{message} | {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"; }}

2.界面显示与日志记录结合

// 注册事件处理程序RecordLogUtil.CommonEvent += MySystemMsg_LogEvent;// 调用显示与记录日志的方法bool result = RecordLogUtil.LogToShow("测试信息", true);

六、窗体实现

1. 几何配置

// 在窗体Load事件中初始化private void FormLog4Net_Load(object sender, EventArgs e){  LogHelper.LoadLogConfig();  // 注册自定义事件处理  RecordLogUtil.CommonEvent += MySystemMsg_LogEvent;  customMsg.CustomEvent += CustomMsg_CustomEvent;}

2. 自定义事件处理

private void MySystemMsg_LogEvent(string message){  if (rtxtDisplay.TextLength >= 10240)  {    rtxtDisplay.Clear();  }  rtxtDisplay.AppendText($"{message}\n");  rtxtDisplay.ScrollToCaret();}private void CustomMsg_CustomEvent(string message){  MySystemMsg_LogEvent(message);}

3. 按钮点击响应

private void btnCommonLogTest_Click(object sender, EventArgs e){  RecordLogUtil.LogToShow("测试通用日志:" + Random().Next(100, 1000), true);  // 注意:这里需要使用Random().Next(100, 1000)生成随机数}private void btnCustomLogTest_Click(object sender, EventArgs e){  customMsg.ShowAndRecordLog("测试自定义日志:" + Random().Next(1000, 10000), true);}

七、运行结果展示

  • 文件路径D:\commonlogD:\log\customLog
  • 日志格式yyyy-MM-dd/yyyyMMdd.'txt'
  • 日志内容<日期和时间> - 信息内容

通过以上配置和实现,可以轻松完成各种日志记录需求,同时满足不同场景下的专业需求。

转载地址:http://jvqnz.baihongyu.com/

你可能感兴趣的文章
MSSQL日期格式转换函数(使用CONVERT)
查看>>
MSTP多生成树协议(第二课)
查看>>
MSTP是什么?有哪些专有名词?
查看>>
Mstsc 远程桌面链接 And 网络映射
查看>>
Myeclipse常用快捷键
查看>>
MyEclipse用(JDBC)连接SQL出现的问题~
查看>>
myeclipse的新建severlet不见解决方法
查看>>
MyEclipse设置当前行背景颜色、选中单词前景色、背景色
查看>>
MyEclipse配置SVN
查看>>
MTCNN 人脸检测
查看>>
MyEcplise中SpringBoot怎样定制启动banner?
查看>>
MyPython
查看>>
MTD技术介绍
查看>>
MySQL
查看>>
MySQL
查看>>
mysql
查看>>
MTK Android 如何获取系统权限
查看>>
MySQL - 4种基本索引、聚簇索引和非聚索引、索引失效情况、SQL 优化
查看>>
MySQL - ERROR 1406
查看>>
mysql - 视图
查看>>