log4net在.NET Core项目中使用案例
1、新建一个 .NET Core 项目,选择控制台应用程序,名称TestNetCore。
2、使用Nuget程序管理器,添加log4net,
3、添加log4net.config,内容如下
<?xml version="1.0" encoding="utf-8"?> <!--注意:如果是在aspnetcore中使用的话,在log4net.config就不需要添加configuration标签了,可以参考TestNetCore的AddLog4Net--> <configuration> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\Log.txt" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaximumFileSize" value="2MB" /> <param name="RollingStyle" value="Size" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%-15p %d [%c] %m%n" /> </layout> </appender> <root> <!--<level value="off" />--> <!--<level value="Fatal" />--> <!--<level value="error" />--> <!--<level value="Warn" />--> <!--<level value="Info" />--> <level value="Debug" /> <!--<level value="all" />--> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
注意:要把log4net.config属性设置成复制到输出目录
4、Program中添加如下
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Globalization; using System.Reflection; using log4net; using System.IO; using log4net.Repository; using log4net.Config; namespace TestNetCore { internal class Program { //public static log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { ILoggerRepository loggerRepository = LogManager.CreateRepository("TestNetCore"); //默认配置,这个只输出到控制台,并且这个不需要log4net.config文件 //BasicConfigurator.Configure(loggerRepository); //指定配置文件 XmlConfigurator.Configure(loggerRepository, new FileInfo("log4net.config")); ILog Log = LogManager.GetLogger(loggerRepository.Name, typeof(Program)); Log.Fatal("Fatal"); Log.Error("Error"); Log.Warn("Warn"); Log.Info("Info"); Log.Debug("Debug"); Console.ReadLine(); } } }
5、运行效果
龙腾一族至尊龙骑