1、打开visual studio 新建控制台项目 Consolelog4net
2、选择项目 Consolelog4net,右键,选择 管理NuGet程序包,搜索log4net,点击安装,
3、新建类App.config文件,内容如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log\Log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="4" />
<maximumFileSize value="10KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<!--<param name="ConversionPattern" value="%-5p %d [%c] [%l] %m%n" />-->
<conversionPattern value="%-5level %date [%thread] - %message %newline" />
</layout>
</appender>
<root>
<level value="all" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
4、新建类LoggerService.cs文件,内容如下
using log4net;
using System.Reflection;
namespace Consolelog4net
{
/// <summary>
/// 日志服务
/// </summary>
public class LoggerService
{
#region Fields and Properties
public static ILog Log { get; } = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static LoggerService()
{
log4net.Config.XmlConfigurator.Configure();
}
#endregion
}
}
5、Program内容如下
using System;
using System.Threading;
namespace Consolelog4net
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("测试log4net的指定日志文件");
while (true)
{
LoggerService.Log.Fatal("Fatal 123");
LoggerService.Log.Error("Error 123");
LoggerService.Log.Warn("Warn 123");
LoggerService.Log.Info("Info 123");
LoggerService.Log.Debug("Debug 123");
//Thread.Sleep(TimeSpan.FromSeconds(1));
}
}
}
}
6、测试
龙腾一族至尊龙骑