H-Mitsumura
H-Mitsumura

Reputation: 11

[nlog]${aspnet-request-ip} is null when I implement log output in .razor and run it in IIS

We are verifying in the following environment.

VS2022 Blazor Server .NET 6.0

When implementing log output in .cshtml.cs and executing it in IIS, the local IP(::1) is output normally. $ {aspnet-request-ip} will be null only if you implement log output in .razor and run it in IIS When debugging with VS (IIS Express), both .cshtml.cs and .razor are output normally.

Could you please tell me what's wrong with my code?

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="Info"
      internalLogFile="${basedir}/logs/internal-nlog-BlazorNLogTest.txt"
      internalLogToConsole="true">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
    <target xsi:type="File" name="logFile" fileName="${aspnet-appbasepath}/logs/nlog-BlazorNLogTest-${shortdate}.log"
            layout="${longdate}|${aspnet-request-ip}||${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--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="logFile" />
  </rules>
</nlog>

Program.cs

using BlazorNLogTest.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using NLog;
using NLog.Web;

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

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

    // DI NLog to ILogger
    builder.Logging.ClearProviders();
    builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    builder.Host.UseNLog();

    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddServerSideBlazor();
    builder.Services.AddSingleton<WeatherForecastService>();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
    }


    app.UseStaticFiles();

    app.UseRouting();

    app.MapBlazorHub();
    app.MapFallbackToPage("/_Host");

    app.Run();
}
catch (Exception exception)
{
    // catch setup errors
    logger.Error(exception, "Stopped program because of exception");
    throw;
}
finally
{
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    NLog.LogManager.Shutdown();
}

Counter.razor

@page "/counter"

@inject ILogger<Counter> _logger

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;

        // Log output (${aspnet-request-ip} is not output when running on IIS)
        _logger.LogDebug("Click!(COUNT={0})", currentCount.ToString());
    }
}

Test.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace BlazorNLogTest.Pages;

public class TestModel : PageModel
{
    [BindProperty]
    [DisplayName("UserId")]
    [Required]
    [StringLength(5)]
    public string? UserId { get; set; }

    private ILogger<TestModel> _logger { get; set; }

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

    public IActionResult OnPost()
    {
        if (ModelState.IsValid is false) return Page();

        // Validate
        if (!(UserId ?? "").Equals("12345"))
        {
            // Log output (${aspnet-request-ip} is output even if executed in IIS)
            _logger.LogDebug(string.Format("NG!(ID={0})", UserId));
            return Page();
        }

        // Log output (${aspnet-request-ip} is output even if executed in IIS)
        _logger.LogDebug(string.Format("OK!(ID={0}, NAME={1})",UserId, "H-Mitsumura"));

        return Redirect(Url.Content("~" + "/"));
    }
}

IIS output log (excerpt)

2022-07-06 16:35:01.2213|||0|DEBUG|Program|init main
2022-07-06 16:35:01.7629|||0|WARN|Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository|Using an in-memory repository. Keys will not be persisted to storage.
2022-07-06 16:35:01.7629|||0|WARN|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
2022-07-06 16:35:01.9215|||0|WARN|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|No XML encryptor configured. Key {6e1761d8-4dea-4c4e-82c5-43f72c923ecd} may be persisted to storage in unencrypted form.
2022-07-06 16:35:07.0661|||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=1)
2022-07-06 16:35:07.5282|||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=2)
2022-07-06 16:35:07.9429|||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=3)
2022-07-06 16:35:08.2966|||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=4)
2022-07-06 16:35:08.6971|||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=5)
2022-07-06 16:35:10.4251|::1||0|ERROR|Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery|An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
2022-07-06 16:35:15.5001|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|NG!(ID=11111)
2022-07-06 16:35:20.6906|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|NG!(ID=12222)
2022-07-06 16:35:25.7533|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|OK!(ID=12345, NAME=H-Mitsumura)

IIS Express output log (excerpt)

2022-07-06 16:40:12.9021|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=1)
2022-07-06 16:40:13.6856|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=2)
2022-07-06 16:40:14.3859|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=3)
2022-07-06 16:40:15.2128|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=4)
2022-07-06 16:40:15.9525|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=5)
2022-07-06 16:40:21.5225|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|NG!(ID=11111)
2022-07-06 16:40:25.7890|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|NG!(ID=12222)
2022-07-06 16:40:30.6269|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|OK!(ID=12345, NAME=H-Mitsumura)

I put all the sources and output logs on GitHub. https://github.com/H-Mitsumura/desktop-tutorial.git

that's all.

It's been a long time, but thank you.

Upvotes: 0

Views: 462

Answers (1)

H-Mitsumura
H-Mitsumura

Reputation: 11

Was self resolved.

IP (::1) is now output when IIS "WebSocket Protocol" is enabled. It seems that "WebSocket Protocol" is always enabled in VS (IIS Express). From now on, if the result is different from VS (IIS Express), I will doubt this.

IIS output log (excerpt)

2022-07-20 16:38:55.2172|||0|DEBUG|Program|init main
2022-07-20 16:38:55.6727|||0|WARN|Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository|Using an in-memory repository. Keys will not be persisted to storage.
2022-07-20 16:38:55.6727|||0|WARN|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
2022-07-20 16:38:55.7914|||0|WARN|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|No XML encryptor configured. Key {c9903561-9d52-439b-92ae-2d4c2cacdb05} may be persisted to storage in unencrypted form.
2022-07-20 16:39:03.2765|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=1)
2022-07-20 16:39:03.4868|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=2)
2022-07-20 16:39:03.7255|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=3)
2022-07-20 16:39:04.0255|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=4)
2022-07-20 16:39:04.6658|::1||0|DEBUG|BlazorNLogTest.Pages.Counter|Click!(COUNT=5)
2022-07-20 16:39:05.9962|::1||0|ERROR|Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery|An exception was thrown while deserializing the token. Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
2022-07-20 16:39:11.3973|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|NG!(ID=11111)
2022-07-20 16:39:15.4945|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|NG!(ID=12222)
2022-07-20 16:39:19.7572|::1||0|DEBUG|BlazorNLogTest.Pages.TestModel|OK!(ID=12345, NAME=H-Mitsumura)

Sorry for the trouble.

Upvotes: 1

Related Questions