First follow the following two packages

Install-Package Microsoft.Extensions.Logging.Debug

Install-Package Microsoft.Extensions.Logging.Log4.AspNetCore

Create log4net.config in the root directory

<? xml version="1.0" encoding="utf-8"? > <log4net> <! -- Define some output appenders --> <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
		<file value="log\log.txt"/ > <! Append log content --> <appendToFilevalue="true"/ > <! --> <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/ > <! - can be as: Once | Size | Date | Composite -- > <! < span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;value="Composite"/ > <! -- Suffix to file name when backing up files --> <datePatternvalue="yyyyMMdd.TXT"/ > <! -- Maximum number of logs, all up to date --> <! --rollingStyle This parameter is available only when the rollingStyle object is SizevalueA log --> <! --rollingStyle if the parameter is Composite, this parameter is available every dayvalue--> <maxSizeRollBackupsvalue="20"/ > <! - the available units: KB | MB | GB - > < maximumFileSizevalue="3MB"/ > <! - set totrueThe current latest log file name is always the name in the file section --> <staticLogFileNamevalue="true"/ > <! -- Output logs between INFO and ERROR --> <filter type="log4net.Filter.LevelRangeFilter">
			<param name="LevelMin" value="ALL" />
			<param name="LevelMax" value="FATAL" />
		</filter>
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
		</layout>
	</appender>
	<root>
		<priority value="ALL"/>
		<level value="ALL"/>
		<appender-ref ref="rollingAppender" />
	</root>
</log4net>
Copy the code

Configuration mode 1: Program

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
   loggingBuilder.AddLog4Net();// A configuration file is required
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();// use Startup to string MVC
});
Copy the code

Configuration method 2: Startup

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            loggerFactory.AddLog4Net();

            app.UseSession();

            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot"))}); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name:"default",
                    pattern: "{controller=Home}/{action=Index}/{id? }");
            });
        }
Copy the code

use

public class FirstController : Controller
    {
        private readonly ILogger<FirstController> _logger;
        private readonly ILoggerFactory _loggerFactory;
        public FirstController(ILogger
       
         logger, ILoggerFactory loggerFactory
       )
        {
            _logger = logger;
            this._loggerFactory = loggerFactory;
        }

        public IActionResult Index()
        {
            this._logger.LogWarning("Log 1");
            this._loggerFactory.CreateLogger<FirstController>().LogWarning("Log 2");
            returnView(); }}Copy the code