1. Create a new .NET Core project, select the console application, and name it TestNetCore.
2. Use Nuget program manager, add log4net ,
3. Add log4net.config as follows
<? xml version = " 1.0 " encoding = " utf-8 " ?> <!-Note: If it is used in aspnetcore, there is no need to add a configuration tag in log4net.config, you can refer to AddLog4Net of TestNetCore-- > <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>
Note: Set the log4net.config property to be copied to the output directory
4. Add the following in 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 " ); // default configuration, this Only output to the console, and this does not need log4net.config file // BasicConfigurator.Configure (loggerRepository); // Specify the configuration file 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. Running effect