在CodeProject上找到一篇关于Log4net的教程:log4net Tutorial,这篇博客的作者是:Tim Corey
,对应源代码地址为:
https://github.com/TimCorey/Log4netTutorial,视频地址为:Application Logging in C#: The log4net tutorial
另外,log4net 主页:http://logging.apache.org/log4net/
Logenet是一个C#的日志库,很方便我们在程序中记录日志,包括日志级别,将日志打印到控制台,或者文件中。
log4net
,然后安装即可。截止2023年12月23日log4net
的最新版本为:2.0.15。如下图所示添加log4net
依赖之后,packages.config
文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.15" targetFramework="net461" />
</packages>
App.config
配置文件中添加关于log4net
的相关配置如下:<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
添加log4net
配置之后的App.config
文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<ConversionPattern value="%date [%thread] %level - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
Program.cs
主程序中引用log4net
,[assembly: log4net.Config.XmlConfigurator(Watch = true)]
(2)、在Program
类中创建一个log4net
的静态对象:
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
(3)、在Main
函数中使用第(2)步中的logger
对象进行日志打印:
logger.Debug("Hello lognet4 tutorial");
logger.Info("Maintenance: water pump turned on");
logger.Warn("Maintenance: the water pump is getting hot");
logger.Error("MonSysPerf.dll load error!");
logger.Fatal("explorer hung");
最终完整的Program.cs
文件如下:
using System;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Log4netTutorial
{
class Program
{
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
logger.Debug("Hello lognet4 tutorial");
logger.Info("Maintenance: water pump turned on");
logger.Warn("Maintenance: the water pump is getting hot");
logger.Error("MonSysPerf.dll load error!");
logger.Fatal("explorer hung");
Console.ReadLine();
}
}
}
运行上述程序,运行结果如下图所示: