Fork me on GitHub
.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/

posted on 2021-12-07 17:02  HackerVirus  阅读(1149)  评论(0编辑  收藏  举报