Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

C# NLog.config なしで NLog を設定するクラスを作ってみた

0
Posted at

はじめに

NLog.config を使わず NLog を設定できる初期化処理のクラスを作ってみました。

環境

  • Visual Studio Community 2022
  • .NET 8.0
  • NLog 6.0.7
  • NLog.Extensions.Logging 6.1.0

ソース

メソッドは Execute() のみのシンプルなクラスです。

NLogInitializer.cs
using NLog;
using NLog.Config;
using NLog.Targets;

namespace SharedLibrary.Utilities;

/// <summary>
/// NLog の初期化処理を提供します。
/// </summary>
public static class NLogInitializer
{
    /// <summary>
    /// NLog の初期化処理を実行します。
    /// </summary>
    public static void Execute()
    {
        var config = new LoggingConfiguration();

        // ログの仕様は以下の通りとします。
        // 1  ログフォルダパス ... exe ファイルと同階層に log フォルダを自動生成する
        // 2. ログファイル名 ... yyyyMMdd.txt で日付毎に自動生成する
        // 3. フォーマット ... yyyy/MM/dd HH:mm:ss [LOG LEVEL] メッセージ 例外情報
        // 4. 保存期間 ... 最大 30 日分のログファイルを保持し、古いものは自動削除する

        var fileTarget = new FileTarget("logfile")
        {
            FileName = "${basedir}/log/${date:format=yyyyMMdd}.txt",
            Layout = "${date:format=yyyy/MM/dd HH\\:mm\\:ss} [${level:uppercase=true:padding=-5:fixedlength=true}] ${message} ${exception:format=tostring}",
            KeepFileOpen = false,
            MaxArchiveDays = 30,
        };

        config.AddTarget(fileTarget);
        config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, fileTarget);

        LogManager.Configuration = config;
    }
}

WPF での実装例です。

App.xaml.cs
/// <summary>
/// <see cref="Application.Startup"/> イベントを発生させます。
/// </summary>
/// <param name="e">イベントデータを格納している <see cref="StartupEventArgs"/>。</param>
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    var services = new ServiceCollection();

    // ロガーを初期化して DI コンテナに登録する。
    NLogInitializer.Execute();
    services.AddLogging(builder =>
    {
        builder.ClearProviders();
        builder.SetMinimumLevel(LogLevel.Trace);
        builder.AddNLog();
    });

    _serviceProvider = services.BuildServiceProvider();
    MainWindow mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
    mainWindow.Show();
}

/// <summary>
/// <see cref="Application.Exit"/> イベントを発生させます。
/// </summary>
/// <param name="e">イベントデータを格納している <see cref="ExitEventArgs"/>。</param>
protected override void OnExit(ExitEventArgs e)
{
    try
    {
        _serviceProvider?.Dispose();
    }
    finally
    {
        LogManager.Shutdown();
        base.OnExit(e);
    }
}

おわりに

政治上 NLog.config を使えない時に実装します。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?