How to use Serilog with Windows Client (net6.0-windows) application

1.4k Views Asked by At

I'm trying to use Serilog and Ninjet on a C# Windows client (forms) application using .Net 6.0

Can anyone tell me how I configure Ninject so that ILogger is injected here:

public partial class TestingForm : Form
{

private readonly ILogger<TestingForm> _logger;

TestingForm(ILogger<TestingForm> logger)
{ 
 _logger = logger;
}
//etc.

}

I was rather hoping to use something like the .UseSeriLog() used here:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog()
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

from https://www.ezzylearning.net/tutorial/logging-in-asp-net-core-5-using-serilog but I just can't work out how to do it with Ninject

1

There are 1 best solutions below

0
thewallrus On

I created a Windows forms app targeting .NET 6. I installed Serilog and Ninject through Nuget.

MyModule.cs:

using Ninject.Modules;
using Serilog;

namespace WinFormsApp1;

public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<ILogger>().To<SeriLogging>();
    }
}

Programs.cs:

internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        var kernel = new StandardKernel(new MyModule());
        var form = kernel.Get<Form1>();
        Application.Run(form);
    }
}

Serilog.cs

public class SeriLogging : ILogger
{
    public void Write(LogEvent logEvent)
    {
        //Implement Serilog here
    }
}

Serilog's ILogger is non-generic so just use ILogger. If you want ILogger of type TestingForm then you probably need to install Microsoft.Extensions.Logging.

using Serilog;

namespace WinFormsApp1;

public partial class Form1 : Form
{
    private readonly ILogger _logger;

    public Form1(ILogger logger)
    {
        InitializeComponent();
        _logger = logger;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _logger.Error("aaaah");
    }
}