- 在ASP.NET Core中依赖注入的方式(非
LogManager.GetLogger
)使用log4net; - Nuget安装2个程序包:log4net、Microsoft.Extensions.Logging.Log4Net.AspNetCore(这个包实现了ILogger和ILoggerProvider这2个接口,.NET Framework不用引用这个程序包);
- 新增配置文件,网上很多配置样本,我的是每天一个日志文件,以“LOG/年/月”做目录,以当天日期命名日志文件;
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="100" />
<param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyy\yyyyMM\yyyyMMdd'.txt'" />
<param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n记录时间:%date %n线程ID:[%thread] %n日志级别: %-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline %n" />
</layout>
</appender>
<root>
<priority value="ALL"/>
<level value="ALL"/>
<appender-ref ref="rollingAppender" />
</root>
- 在Program.cs里为HostBuilder配置Log4net
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(log =>
{
log.ClearProviders();
log.AddFilter("System", LogLevel.Warning);
log.AddFilter("Microsoft", LogLevel.Warning);
log.AddLog4Net("CFGFiles/log4net.config");
}).ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
- 在Home控制器里依赖注入并使用
public class HomeController : Controller
{
private readonly ILogger _Log;
public HomeController(ILogger<HomeController> logger)
{
this._Log = logger;
}
public IActionResult Index()
{
_Log.LogInformation($"日志记录 LogInformation:{this.GetType()}");
return View();
}
}
- 结果截图