2
votes

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:

I try to do this in an Winforms Application

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

Thank you

1
You could setup dependency injection using the generic host, then just get a scoped ILogger<T>.Jeremy Lakeman
Have you tried AddDebug() and see if it does something?Mike Nakis
In other words, how do you know "it just does nothing"? Where have you checked? The console is not available in winforms applications, and messages in the windows event log might be hard to find. But visual studio will show debug messages in the output window.Mike Nakis
@MikeNakis Yes I did, but I got no output from it.LucaScript
Okay, well, here is my two cents worth: I don't use logging libraries. Logging is just slightly more complicated than trivial, so it is very easy to do it yourself, whereas my experience with logging libraries is that they invariably require way too much troubleshooting and puzzling over why they don't work to be worth the trouble they save you. In these libraries they intentionally follow a "we never generate errors" doctrine, which means that troubleshooting them is virtually impossible. That's a lame doctrine. When something does not work, I want to see ERRORs. Plenty of ERRORs.Mike Nakis

1 Answers

4
votes

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.