0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MiniAPI(十九)導入NLogの取り組み

Posted at

本連載の第8回では、標準のログ機能について話し合いましたが、より柔軟で強力で便利なロギングシステムを求める場合、標準の機能では不十分な場合があります。今回は、そのようなニーズに応える強力で柔軟、便利なログライブラリであるNLogと、それをMiniAPIで使用する方法について紹介します。

まずは、NuGetパッケージNLog.Web.AspNetCoreを導入します。コードの実装は非常にシンプルです。

using NLog;
using NLog.Web;

// ロガーの起動
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");
try
{
    var builder = WebApplication.CreateBuilder(args);
    // ログの設定
    builder.Logging.ClearProviders();
    builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    builder.Host.UseNLog();

    var app = builder.Build();
    // ログの使用
    app.MapGet("/logtest", () =>
    {
        app.Logger.LogTrace("LogTrace");
        app.Logger.LogDebug("LogDebug");
        app.Logger.LogWarning("LogWarning");
        app.Logger.LogInformation("LogInformation");
        app.Logger.LogError("LogError");
        app.Logger.LogCritical(new Exception("eLogCritical"), "LogCritical");
        return "logtest";
    });
    app.MapGet("/myvalue", MyService.GetMyValue);
    app.Run();
}
catch (Exception exception)
{
    // 例外時のログ処理
    logger.Fatal(exception, "Stopped program because of exception");
}
finally
{
    NLog.LogManager.Shutdown();
}

class MyService
{
    public static string GetMyValue(ILogger<MyService> logger)
    {
        logger.LogInformation("TestService.GetMyValue");
        return "MyValue";
    }
}

NLogの便利さは、その設定の豊富さにあります。ログの方式や情報の収集項目を柔軟に設定できます。NLogの設定は、プロジェクトのルートディレクトリにnlog.configファイルとして保存されます。もちろん、起動ログのLoadConfigurationFromAppSettingsを変更してnlog.configのパスを設定することも可能です。

設定は主にtargetsノードとrulesノードを使用して実施されます。targetsはログの保存や表示の方式(テキストファイル、JSONファイルなど)やログの内容をlayoutで設定します。具体的なtargetの属性については、https://github.com/NLog/NLog/wiki/File-target を参照してください。layoutについては、https://nlog-project.org/config/?tab=layout-renderers で確認できます。

rulesは異なる機能モジュールやログレベルなどの情報を設定します。詳細は https://github.com/nlog/nlog/wiki/Configuration-file#rules を参照してください。

以下の例では、公式テンプレートに含まれるallfileとownFile-webの2つのテキストファイルテンプレートと、jsonfileテンプレート、及びカラー化されたコンソールテンプレートが設定されています。(それぞれのテンプレートの属性については公式ドキュメントを参照してください。)

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"      internalLogLevel="Info">
  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- 以下略 -->
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!-- 以下略 -->
  </rules>
</nlog>

appsettings.jsonの設定は以下の通りです。

{
  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft.AspNetCore": "Trace"
    }
  },
  "AllowedHosts": "*"
}

設定に基づき、実際の効果を確認してみましょう。コンソール結果、.json結果、逐一ログファイルの結果を確認すると、設定した通りのログ情報が得られます。

(Translated by GPT)

元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247484964&idx=1&sn=ab55ffce2744025450dd56d5c2bef1b4&chksm=9f00590ea877d0188e7621e5799dac6e2e6969a2100a84cad7f688ea03f4e4967c4624b1f38d&token=877361727&lang=zh_CN#rd

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?