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

 

转载:https://blog.csdn.net/dnazhd/article/details/89555517

 

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、运行结果

 


————————————————

posted @ 2021-09-15 13:48  梅长苏枫笑  阅读(444)  评论(0编辑  收藏  举报