博客
关于我
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/

你可能感兴趣的文章
MySQL Order By实现原理分析和Filesort优化
查看>>
mysql problems
查看>>
mysql replace first,MySQL中处理各种重复的一些方法
查看>>
MySQL replace函数替换字符串语句的用法(mysql字符串替换)
查看>>
Mysql Row_Format 参数讲解
查看>>
mysql select, from ,join ,on ,where groupby,having ,order by limit的执行顺序和书写顺序
查看>>
MySQL Server 5.5安装记录
查看>>
mysql slave 停了_slave 停止。求解决方法
查看>>
MySQL SQL 优化指南:主键、ORDER BY、GROUP BY 和 UPDATE 优化详解
查看>>
mysql sum 没返回,如果没有找到任何值,我如何在MySQL中获得SUM函数以返回'0'?
查看>>
mysql Timestamp时间隔了8小时
查看>>
Mysql tinyint(1)与tinyint(4)的区别
查看>>
mysql union orderby 无效
查看>>
mysql where中如何判断不为空
查看>>
mysql workbench6.3.5_MySQL Workbench
查看>>
MySQL Workbench安装教程以及菜单汉化
查看>>
MySQL Xtrabackup 安装、备份、恢复
查看>>
mysql [Err] 1436 - Thread stack overrun: 129464 bytes used of a 286720 byte stack, and 160000 bytes
查看>>
MySQL _ MySQL常用操作
查看>>
MySQL – 导出数据成csv
查看>>