.Net 6 Log4Net File Logging in ASP.NET Core


Log4Net File Logging in ASP.NET Core

Logging Using Log4Net in ASP.NET Core

今天在這篇文章中,我們將看到如何在ASP.NET Core API應用程序中使用Log4Net進行文件/滾動文件日志記錄和控制台日志記錄。

在.NET Core 2.2和.NET Core 3.1 +以后的框架中,日志記錄被進一步簡化。在上一篇文章中,我們看到了如何在ASP.NET Core WebAPI中使用內置提供程序啟用日志。

我們將利用DI(依賴注入)框架將Log4Net記錄器對象注入到ASP.NET Core API管道中。

請注意,文件/滾動文件日志提供者仍然無法通過.NET核心框架獲得,我們需要依靠外部解決方案,今天我們將看到如何使用Log4Net來解決同樣的需求。

微軟建議使用第三方記錄器框架,如Serlilog或Log4Net或NLog來滿足其他高端記錄需求,如數據庫或文件/滾動文件記錄。

在這篇文章中,我們將了解如何使用Log4Net啟用文件/滾動文件日志,並通過一個例子對現有行為進行定制。

 

Getting started

 

Create ASP.NET Core 3.1 or .NET 5 & 6 + application,

 

Logging Using Log4Net in ASP.NET Core

 

 

Log4Net For ASP.NET Core is available through NuGet packages.

 

Please use the latest available version for ASP.NET Core version.

 

Please add below NuGet Packages,

 

PM> Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 3.1.0

 

Or

Please install the package through Nuget Package Manager,

 

Logging Using Log4Net in ASP.NET Core

 

 

Update Main() method

 

Please update the Main method for adding the rolling file as shown in below-highlighted code in Program.cs

 

Enable File Logging in ASP.NET Core

 

Update CreateHostBuilder() method for Log4Net as below using ConfigureLogging().

 

1
2
3
4
5
6
7
8
9
10
public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.UseStartup<Startup>();
               }).ConfigureLogging(builder =>
               {
                   builder.SetMinimumLevel(LogLevel.Trace);
                   builder.AddLog4Net("log4net.config");
               });

 

Lets now use logging in Controller using regular ILogger Interface. Here below Controller uses ILogger interface using Dependency injection.

 

Rolling file Logging Using Log4Net in ASP.NET Core

 

Please see below sample implementation of our Controller,

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[Route("api/[controller]")]
    [ApiController]
    public class LoggingController : ControllerBase
    {
        private readonly ILogger _logger;
 
        public LoggingController(ILogger<LoggingController> logger)
        {
            _logger = logger;
        }
        // GET api/values
        [HttpGet("{id}")]
        public ActionResult<IEnumerable<string>> Get(int id)
        {
            _logger.LogInformation("Start : Getting item details for {ID}", id);
 
            List<string> list = new List<string>();
            list.Add("A");
            list.Add("B");
            list.Add("C");
 
            _logger.LogInformation($"Completed : Item details are { string.Join(", ", list) }");
            return list;
        }

 

Let’s execute the code and verify the generated file.

 

The log file will be created in the project directory and logging will be captured as shown below figure.

 

You can enable logging on any controller or any other layer of your API like the Business or domain layer easily. Also as shown above logging can be enabled on Startup.cs and Program.cs files as well.

 

Below shows an example of file logging created by Log4Net,

 

File Logging Using Log4Net in ASP.NET Core

 

Log4Net supports different types of logging using different types of logging appender. Please use the required appenders as appropriate.

 

File Logging Appender

 

If you wish to enable only File/Rolling File logging appender , please use the File appender in the log4net file as below,

Sample log4net.config file used is as below,

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="TheCodeBuzz.log" />
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="TRACE" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

 

What is a Rolling file?

By configuring the log file as rolling, you get the capability to create a logging file based on dates or file size or name format, and many more custom options. Your file keeps rolling as per provided criteria.

 

Console Logging Appender

 

If you wish to enable only Console logging with the customized format of log message please use Console appender as below ,

 

1
2
3
4
5
6
7
8
9
<appender name="Console" type="log4net.Appender.ConsoleAppender">
   <layout type="log4net.Layout.PatternLayout">
     <!-- Pattern to output the caller's file name and line number -->
     <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
   </layout>
</appender>
 
   <appender-ref ref="ConsoleAppender" />
</root>

 

Console logging will be displayed on the console as below,

 

Console Logging Using Log4Net in ASP.NET Core

 

That’s all , Hope this article was helpful.

 

One can use the same concept for .NET Core Console/Desktop Application logging as well.

 

Summary

 

It’s very easy to configure file logging in ASP.NET Core using the Log4Net NuGet package. Log4Net helps us enabling logging in a few simple steps and addresses the file-based and other types of logging requirements easily.

https://www.c-sharpcorner.com/technologies

https://www.thecodebuzz.com/log4net-file-logging-console-logging-asp-net-core/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM