Hide Lab@はてなブログ

主にC#で活動しています。

ASP.NET Core 6 で NLog を使用してログ出力

はじめに

ロギングを行うライブラリは沢山ありますが、比較的導入が簡単な NLog を DI を利用してログ出力する方法を紹介します。

開発環境

準備

以下のパッケージを手動または nuget を使用して追加してください。

  • NLog.Web.AspNetCore v5+
  • NLog v5+

nlog.config ファイルの作成

プロジェクトのルートに nlog.config (すべて小文字) ファイルを作成します。

以下サンプルです。

<?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="off"
       throwConfigExceptions="false"
      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">
    <!--出力先-->
    <variable name="logDirectory" value="c:\temp" />
    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <!-- the targets to write to -->
    <targets async="true">
        <!-- File Target for all log messages with basic details -->
        <target xsi:type="File" name="allfile" fileName="${logDirectory}\nlog-AspNetCore-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
        <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="${logDirectory}\nlog-AspNetCore-own-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />
        <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
        <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Info" writeTo="allfile" />
        <!--Output hosting lifetime messages to console target for faster startup detection -->
        <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
        <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
        <logger name="Microsoft.*" maxlevel="Info" final="true" />
        <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    </rules>
</nlog>

Program.csの更新

using NLog;
using NLog.Web;

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");

try
{
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.
    builder.Services.AddControllersWithViews();

    // NLog をセットアップする
    builder.Logging.ClearProviders();
    builder.Host.UseNLog();

    var app = builder.Build();

    builder.Services.AddLogging();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/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.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    app.Run();
}
catch (Exception exception)
{
    //NLog セットアップ エラー
    logger.Error(exception, "例外のためプログラムを停止しました");
    throw;
}
finally
{
    // アプリケーションが終了する前に、内部タイマー/スレッドをフラッシュして停止するようにします (Linux でのセグメンテーション違反を回避します)
    NLog.LogManager.Shutdown();
}

使用例

using Microsoft.AspNetCore.Mvc;

namespace HideLab.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            this._logger = logger;
        }

        public IActionResult Index()
        {
            this._logger.Log(LogLevel.Information, "Hello hoge");
            return View();
        }
    }
}