C#一个完整的Log4net使用实例

Log4net库是.Net下一个非常优秀的开源日志记录组件,是一个帮助程序员将日志信息输出到各种目标(控制台、文件、数据库等)的工具。它具有:支持多数框架、可输出日志到多种目标、层级日志体系、可使用XML配置、可动态配置、模块化和可扩展化设计、灵活、高性能等特征。

日志记录器(Logger)的行为是分等级的,一般可分为5种日志等级(Level),优先级从高到低:

1、FATAL(致命错误):记录系统中出现的能使用系统完全失去功能,服务停止,系统崩溃等使系统无法继续运行下去的错误。例如,数据库无法连接,系统出现死循环。

2、ERROR(一般错误):记录系统中出现的导致系统不稳定,部分功能出现混乱或部分功能失效一类的错误。例如,数据字段为空,数据操作不可完成,操作出现异常等。

3、WARN(警告):记录系统中不影响系统继续运行,但不符合系统运行正常条件,有可能引起系统错误的信息。例如,记录内容为空,数据内容不正确等。

4、INFO(一般信息):记录系统运行中应该让用户知道的基本信息。例如,服务开始运行,功能已经开户等。

5、DEBUG (调试信息):记录系统用于调试的一切信息,内容或者是一些关键数据内容的输出。

我们可以控制到应用程序中相应级别的日志信息的开关。比如在定义了INFO级别, 则应用程序中所有DEBUG级别的日志信息将不被打印出来。

使用实例:

1、新建WPF应用程序LogDemo;

2、在项目中添加对log4net.dll的引用,这里引用版本是2.0.8.0。

3、在App.config文件中添加配置信息;

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!--log4net配置start-->
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender_DateFormat" type="log4net.Appender.RollingFileAppender">
      <file value="D:/Log/Demo_"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy-MM-dd&quot;.log&quot;"/>
      <staticLogFileName value="false"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread](%file:%line) %-5level %logger [%property{NDC}] - %message%newline"/>
      </layout>
    </appender>
    <root>
      <appender-ref ref="RollingLogFileAppender_DateFormat"/>
    </root>
  </log4net>
  <!--log4net配置end-->
  <startup> 
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
</configuration>

4、在AssemblyInfo.cs中添加配置项

//Log4net.config配置文件
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]

5、新建XML文件夹添加Config.xml配置文件

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <!--日志等级-->
  <LogLevel>0</LogLevel>
  <!--日志目录-->
  <LogFilePath>D:/Log</LogFilePath>
  <!--日志存在天数-->
  <LogFileExistDay>1</LogFileExistDay>
</appSettings>

注意修改Config.xml文件属性: 

6、新建Utility文件夹,分别添加日志记录类LogHelper.cs、全局使用参数类Parameter.cs、XML文件读取类XMLHelper.cs;

LogHelper.cs

using System;
using System.Reflection;
using static LogDemo.Utility.Parameter;

namespace LogDemo.Utility
{
    /// <summary>
    /// Fatal级别的日志由系统全局抓取
    /// </summary>
    public class LogHelper
    {
        public static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static void Debug(object messsage)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Debug)
            {
                log.Debug(messsage);
            }
        }

        public static void DebugFormatted(string format, params object[] args)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Debug)
            {
                log.DebugFormat(format, args);
            }
        }

        public static void Info(object message)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Info)
            {
                log.Info(message);
            }
        }

        public static void InfoFormatted(string format, params object[] args)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Info)
            {
                log.InfoFormat(format, args);
            }
        }

        public static void Warn(object message)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Warn)
            {
                log.Warn(message);
            }
        }

        public static void WarnFormatted(string format, params object[] args)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Warn)
            {
                log.WarnFormat(format, args);
            }
        }

        public static void Error(object message)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Error)
            {
                log.Error(message);
            }
        }

        public static void Error(object message, Exception exception)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Error)
            {
                log.Error(message, exception);
            }
        }

        public static void ErrorFormatted(string format, params object[] args)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Error)
            {
                log.ErrorFormat(format, args);
            }
        }

        public static void Fatal(object message)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Fatal)
            {
                log.Fatal(message);
            }
        }

        public static void Fatal(object message, Exception exception)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Fatal)
            {
                log.Fatal(message, exception);
            }
        }

        public static void FatalFormatted(string format, params object[] args)
        {
            if ((int)Parameter.LogLevel <= (int)LogLevelEnum.Fatal)
            {
                log.FatalFormat(format, args);
            }
        }
    }
}

Parameter.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LogDemo.Utility
{
    public class Parameter
    {
        /// <summary>
        /// 日志等级
        /// </summary>
        public enum LogLevelEnum
        {
            Debug = 0,
            Info = 1,
            Warn = 2,
            Error = 3,
            Fatal = 4
        }

        /// <summary>
        /// 当前保存日志等级
        /// </summary>
        public static LogLevelEnum LogLevel;

        /// <summary>
        /// 日志存放路径
        /// </summary>
        public static string LogFilePath;

        /// <summary>
        /// 日志存放天数
        /// </summary>
        public static int LogFileExistDay;
    }
}

XMLHelper.cs

using System;
using System.IO;
using System.Xml;
using static LogDemo.Utility.Parameter;

namespace LogDemo.Utility
{
    public static class XMLHelper
    {
        public static void ReadXml()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XML", "Config.xml"));
                var node = doc.SelectSingleNode("appSettings");
                Parameter.LogLevel = (LogLevelEnum)Enum.Parse(typeof(LogLevelEnum), node.SelectSingleNode("LogLevel").InnerText);
                Parameter.LogFilePath = node.SelectSingleNode("LogFilePath").InnerText;
                Parameter.LogFileExistDay = int.Parse(node.SelectSingleNode("LogFileExistDay").InnerText);

                LogHelper.Debug("XML文件读取成功。");
            }
            catch (Exception ex)
            {
                LogHelper.log.Error(string.Format("XML文件读取失败。{0}", ex));
            }
        }
    }
}

7、在App.xaml.cs中添加系统全局抓取日志记录

using LogDemo.Utility;
using System.Windows;

namespace LogDemo
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            LogHelper.Fatal(e.Exception);//添加系统全局抓取日志记录
            e.Handled = true;
        }
    }
}

8、主界面xaml

<Window x:Class="LogDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:LogDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="现在可以查看日志了" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="32"></Label>
    </Grid>
</Window>

 9、交互逻辑

using LogDemo.Utility;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace LogDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            //读取XML配置信息
            XMLHelper.ReadXml();
            //日志清除
            Task.Factory.StartNew(() =>
            {
                DirectoryInfo di = new DirectoryInfo(Parameter.LogFilePath);
                if (!di.Exists)
                    di.Create();
                FileInfo[] fi = di.GetFiles("Demo_*.log");
                DateTime dateTime = DateTime.Now;
                foreach (FileInfo info in fi)
                {
                    TimeSpan ts = dateTime.Subtract(info.LastWriteTime);
                    if (ts.TotalDays > Parameter.LogFileExistDay)
                    {
                        info.Delete();
                        LogHelper.Debug(string.Format("已删除日志。{0}", info.Name));
                    }
                }
                LogHelper.Debug("日志清理完毕。");
            });
        }
    }
}

10、项目结构 

11、运行结果

  • 14
    点赞
  • 129
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
下面是一个简单的 C# LOG4NET 实例: 首先,需要在项目中添加 log4net 库的引用。 然后,在代码中引入 log4net 的命名空间: ```csharp using log4net; using log4net.Config; ``` 在代码中定义一个静态变量,表示 log4net 的日志记录器: ```csharp private static readonly ILog log = LogManager.GetLogger(typeof(Program)); ``` 在程序启动时,需要初始化 log4net 配置: ```csharp XmlConfigurator.Configure(new FileInfo("log4net.config")); ``` 在代码中使用 log4net 记录日志: ```csharp log.Info("This is an info message"); log.Warn("This is a warning message"); log.Error("This is an error message", exception); ``` 其中,log.Info、log.Warn、log.Error 等方法表示不同级别的日志记录。exception 是一个异常对象,用于记录异常信息。 最后,在项目根目录下创建一个名为 log4net.config 的文件,配置 log4net 的具体参数,如: ```xml <?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="FileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/log.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="5" /> <maximumFileSize value="10MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="FileAppender" /> </root> </log4net> ``` 这个配置文件指定了日志记录器的具体参数,如日志文件的名称、大小限制等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RunnerDNA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值