Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instance an Logger in C# .net Core 3.1

I'm interested in using the Microsoft.Extensions.Logging class for logging in a Project.

I searched for around 4 hours, watched an tutorial which was about one hour and just could not figure out how to instance a logger in C# (most tutorials use ASP.Net)

What I tried:

        var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder
                .AddConsole()
                .AddEventLog();
        });
        ILogger logger = loggerFactory.CreateLogger<Form1>();
        logger.LogInformation("Example log message");

This code is copied from the Microsoft Website (with some slight changes), it dosent give me Syntax Errors or warnings, but also it just does nothing.

I allready were on those links:

  • https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
  • https://learn.microsoft.com/en-us/archive/msdn-magazine/2016/april/essential-net-logging-with-net-core
  • https://www.tutorialsteacher.com/core/fundamentals-of-logging-in-dotnet-core
  • https://www.tutorialsteacher.com/core/aspnet-core-logging And many more

I try to do this in an Winforms Application

Maybe you allready did something simular in C# and .net Core.

Thank you

like image 298
LucaScript Avatar asked Oct 20 '25 15:10

LucaScript


1 Answers

I decided to try out your code in a WinForms app and see for myself. You actually are logging but you are not seeing the logs. I recommend adding a logging library and adding a file sink or similar.

Here's how you can add a console window where your logging could be visible: In Program add:

    internal static class NativeMethods
    {
        [DllImport("kernel32.dll")]
        internal static extern Boolean AllocConsole();
    }

Now, in your Main method add:

NativeMethods.AllocConsole();

This will open the console window and in it you'll see your example log message.

like image 199
milosponj Avatar answered Oct 23 '25 03:10

milosponj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!