Apache log4net™ กับ .NET 6 WebApi

สร้างโปรเจ็กส์แบบ ASP.NET Core Web API

1. ทดสอบ logger

ที่ไฟล์ Controllers/WeatherForecastController.cs เพิ่มโค๊ด _logger.* ไว้ดูผลการ log

using Microsoft.AspNetCore.Mvc;

namespace WebApi1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogInformation("This is an INFORMATION message.");
            _logger.LogWarning("This is a WARNING message.");
            _logger.LogError("This is an ERROR message.");

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

เปิดหน้าต่าง Output โดยไปที่เมนู View | Output

ทดลองเรียก WeatherForecast เช่น https://localhost:7244/WeatherForecast แล้วดูที่หน้าต่าง Output

WebApi1.Controllers.WeatherForecastController: Information: This is an INFORMATION message.
WebApi1.Controllers.WeatherForecastController: Warning: This is a WARNING message.
WebApi1.Controllers.WeatherForecastController: Error: This is an ERROR message.

2. ใช้ log4net

ติดตั้ง Package log4net และ Microsoft.Extensions.Logging.Log4Net.AspNetCore

PM> Install-Package log4net -Version 2.0.13
PM> Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 6.0.0
PM> NuGet\Install-Package log4net -Version 2.0.15
PM> NuGet\Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 6.1.0

สร้างไฟล์ log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="log/" />
    <datePattern value="yyMMdd'Jack.log'" />
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <encoding value="UTF-8"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%-5p%d{ HH:mm:ss} li:%line - [%method] %m  %n" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="RollingLogFileAppender"/>
  </root>
</log4net>

หรือ

<log4net>
	<root>
		<level value="ALL" />
		<appender-ref ref="file" />
	</root>
	<appender name="file" type="log4net.Appender.RollingFileAppender">
		<file value="net6demo.log" />
		<appendToFile value="true" />
		<rollingStyle value="Size" />
		<maxSizeRollBackups value="5" />
		<maximumFileSize value="10MB" />
		<staticLogFileName value="true" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
		</layout>
	</appender>
</log4net>

.NET 5 แก้ไขไฟล์ Start.cs

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "EWBranchAPI", Version = "v1" });
            });

            ILoggerFactory _loggerFactory = (ILoggerFactory)new LoggerFactory();
            _loggerFactory.AddLog4Net();
            services.AddSingleton(_loggerFactory);
        }

.NET 6 แก้ไขไฟล์ Program.cs

var builder = WebApplication.CreateBuilder(args);

ILoggerFactory _loggerFactory = (ILoggerFactory)new LoggerFactory();
_loggerFactory.AddLog4Net();
builder.Services.AddSingleton(_loggerFactory);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

ทดลองเรียก WeatherForecast อีกครั้งจะได้ไฟล์ .log

2021-12-15 21:21:44,620 [.NET ThreadPool Worker] INFO WebApi1.Controllers.WeatherForecastController - This is an INFORMATION message.
2021-12-15 21:21:44,641 [.NET ThreadPool Worker] WARN WebApi1.Controllers.WeatherForecastController - This is a WARNING message.
2021-12-15 21:21:44,643 [.NET ThreadPool Worker] ERROR WebApi1.Controllers.WeatherForecastController - This is an ERROR message.

Number of levels recorded for each setting level:

 ALL    DEBUG   INFO    WARN    ERROR   FATAL   OFF
•All                        
•DEBUG  •DEBUG                  
•INFO   •INFO   •INFO               
•WARN   •WARN   •WARN   •WARN           
•ERROR  •ERROR  •ERROR  •ERROR  •ERROR      
•FATAL  •FATAL  •FATAL  •FATAL  •FATAL  •FATAL  
•OFF    •OFF    •OFF    •OFF    •OFF    •OFF    •OFF