准备log4net配置文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
<file value="log/log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMM/yyyy-MM-dd.log" />
<maxSizeRollBackups value="20" />
<maximumFileSize value="3MB" />
<staticLogFileName value="true" />
<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>
设置文件始终复制
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/964beeecb409813294f965b91e8cec13.png)
Program.cs 配置
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
#region log4net 的代码
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.AddLog4Net(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "configs", "log4net.xml"));
})
#endregion log4net 的代码
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
运行程序,查看写入文本文件的日志:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/565ce30dc4b95d12f94adeb9d5980f7a.png)