Featured
Setup Log4net logging on ASP.NET 5
Last modified: June 13, 2021Step 1
Create an ASP.NET Core MVC application.
Step 2
We need to install log4net nuget packages. You can either install them via nuget package manager or simply edit the log4net_demo.csproj file.
<ItemGroup>
<PackageReference Include="log4net" Version="2.0.12" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="5.0.1" />
</ItemGroup>
Step 3
Create a file named log4net.config in the root level and copy the below code.
We will saved the log file to "C:\Temp" folder <file value="C:\Temp\" />
. The file name has a convention of date <datePattern value="yyyy-MM-dd.'txt'"/>
(e.g. 2021-06-13.txt). Every new day new file will create <rollingStyle value="Date"/>
. Total number of log files in the folder will be 100 <maxSizeRollBackups value="100"/>
. The maximum file size is 100 MB.
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="C:\Temp\" />
<datePattern value="yyyy-MM-dd.'txt'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="100MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level App %newline %message %newline %newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
Step 4
In the Program.cs we need to edit main function as below.
public static void Main(string[] args)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
CreateHostBuilder(args).Build().Run();
}
Step 5
Finally in the startup.cs file, we first inject ILoggerFactory and then add loggerFactory.AddLog4Net();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
loggerFactory.AddLog4Net();