Search code examples
c#blazor-server-sideiloggernreco

Log not updating in file for other project in solution using Ilogger factory and Nreco in Blazor


I have some projects in a solution where the main project is Blazor Server. I have installed Nreco logger in the Blazor Project to post various logs.

Program.cs

using BlazorApp;
using BlazorApp.Components;

using TestProj.Models;

using NReco.Logging.File;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddLogging(bldr =>
{
    bldr.AddFile("testlog.txt"), options =>
    {
        options.Append = true;
        options.FileSizeLimitBytes = 20480;
        options.MaxRollingFiles = 20;
    });
});

PersonModel.LogrFctry = LoggerFactory.Create((bldr) => { });


WebApplication app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

My PersonModel has a static property

public static ILoggerFactory GlobLogrFctry { get; set; }

which I use it to create Ilogger<> object there.

Now when I post logs in the person model object, it appears on console but not on file. How to post these logs also in the file. Any suggestions would be greatly appreciated.

Note : The code and technique might not look like a global standard as I am just testing this in a separate experimental project.


Solution

  • The issue here is that you are creating a separate instance of IloggerFactory which is not the one of Nreco. You can use already instantiated object like:

    PersonModel.LogrFctry = app.Services.GetRequiredService<ILoggerFactory>();
    

    after Build();

    And as you have stated that this is a test project, I will ignore the location of IloggerFactory property which should be on a global reachable class.