星期二, 12月 19, 2023

[.NET] 在 BackgroundService 內使用 NLog

在 BackgroundService 內使用 NLog 5.2.7 來處理 Log,主要進行三種輸出,分別為 txt 檔案、DB 和 Console,NLog 相關請參考之前筆記
NLog 5.2.7 在筆記時官方說明還沒有 .NET 8 在上面,但可以進行安裝,DB 連線部分則是安裝 Microsoft.Data.SqlClinet 來使用,而非 System.Data.SqlClient,下圖為安裝套件



Programes
using NLog.Config;
using NLog.Extensions.Logging;
using NLog.Targets;

namespace NLogWorkerSample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
            builder.Services.AddHostedService<Worker>();

            builder.Logging.ClearProviders();
            builder.Logging.AddNLog(NLogConfigurationInit());

            var host = builder.Build();
            host.Run();
        }

        private static LoggingConfiguration NLogConfigurationInit()
        {
            LoggingConfiguration config = new LoggingConfiguration();

            // Target 1:把錯誤訊息輸出至 txt 檔案 
            FileTarget errorFile = new FileTarget("errorfile") { FileName = @"D:\ErrorFile.txt" };
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, errorFile);

            // Target 2:把錯誤訊息 insert 至 DB 
            DatabaseTarget target = new DatabaseTarget();
            target.ConnectionString = "Data Source=.;Initial Catalog=AdventureWorks2022;Integrated Security=True;TrustServerCertificate=True";
            target.CommandText = "insert into LogTable(LogTime,Message) values(@LogTime, @Message);";
            target.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogTime", Layout = "${date}" });
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, target);

            // Target 3:把錯誤訊息輸出至 Console
            ColoredConsoleTarget coloredConsole = new ColoredConsoleTarget("ColoredConsole");
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, coloredConsole);

            return config;
        }
    }
}

.NET 8 預設 Worker 範本
namespace NLogWorkerSample
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

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

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                }
                await Task.Delay(1000, stoppingToken);
            }
        }
    }
}

執行結果

寫進 txt 檔案


  DB insert
 


Console 輸出

沒有留言:

張貼留言