- Log4Net for Logging in Windows Form Desktop Application | TheCodeBuzz
- dependency injection in Windows forms and EF core – Microsoft Q&A
สร้างโปรเจ็กส์แบบ Windows Forms App (winforms) ชื่อ WinFormsApp1
ดูไฟล์ Program.cs
namespace WinFormsApp1 { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } }
ดูไฟล์ Form1.cs
namespace WinFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
ติดตั้ง Package log4net
, Microsoft.Extensions.Hosting
และ Microsoft.Extensions.Logging.Log4Net.AspNetCore
ดูไฟล์ WinFormsApp1.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>WinExe</OutputType> <TargetFramework>net6.0-windows</TargetFramework> <Nullable>enable</Nullable> <UseWindowsForms>true</UseWindowsForms> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="log4net" Version="2.0.15" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" /> <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="6.1.0" /> </ItemGroup> </Project>
สร้างไฟล์ log4net.config และ ตั้งค่า Copy to Output Directory เป็น Copy always
<?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
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WinFormsApp1 { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); ///Generate Host Builder and Register the Services for DI var builder = new HostBuilder() .ConfigureServices((hostContext, services) => { //Register all your services here services.AddLogging(configure => configure.AddConsole()) .AddScoped<Form1>(); }).ConfigureLogging(logBuilder => { logBuilder.SetMinimumLevel(LogLevel.Trace); logBuilder.AddLog4Net("log4net.config"); }); var host = builder.Build(); using (var serviceScope = host.Services.CreateScope()) { var services = serviceScope.ServiceProvider; try { var form1 = services.GetRequiredService<Form1>(); Application.Run(form1); Console.WriteLine("Success"); } catch (Exception ex) { Console.WriteLine("Error"); Console.WriteLine(ex.ToString()); } } } } }
แก้ไขไฟล์ Form1.cs
using Microsoft.Extensions.Logging; namespace WinFormsApp1 { public partial class Form1 : Form { private readonly ILogger _logger; public Form1(ILogger<Form1> logger) { InitializeComponent(); _logger = logger; try { _logger.LogInformation("Form1 Started"); MessageBox.Show("Hello World!"); } catch (Exception ex) { _logger.LogError(ex.Message); } } } }