สร้างโปรเจ็กส์แบบ ASP.NET Core Web App
1. ทดสอบ logger
ที่ไฟล์ Pages/Index.cshtml.cs เพิ่มโค๊ด _logger.* ไว้ดูผลการ log
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApp6.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
_logger.LogInformation("This is an INFORMATION message.");
_logger.LogWarning("This is a WARNING message.");
_logger.LogError("This is an ERROR message.");
}
}
}
เปิดหน้าต่าง Output โดยไปที่เมนู View | Output
ทดลองเรียกไปที่หน้า Home เช่น https://localhost:7138/ แล้วดูที่หน้าต่าง Output
WebApp6.Pages.IndexModel: Information: This is an INFORMATION message. WebApp6.Pages.IndexModel: Warning: This is a WARNING message. WebApp6.Pages.IndexModel: Error: This is an ERROR message.
2. ใช้ log4net
ติดตั้ง Package log4net และ Microsoft.Extensions.Logging.Log4Net.AspNetCore
- NuGet Gallery | log4net 2.0.15
- NuGet Gallery | Microsoft.Extensions.Logging.Log4Net.AspNetCore 6.1.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>
แก้ไขไฟล์ 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.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
ทดลองเรียกหน้า Home อีกครั้งจะได้ไฟล์ .log