How does Microsoft.Extensions.Logging work for full .net framework?

Raghu picture Raghu · Feb 21, 2017 · Viewed 23.2k times · Source

The article (Monitor and diagnose Azure Service Fabric applications) indicates following (please note text in bold):

ASP.NET Core logging

Choosing how to instrument your code can be difficult, if you chose poorly and have to reinstrument, you are revisiting and potentially destabilizing your code base. To reduce the risk, developers can choose an instrumentation library such as Microsoft.Extensions.Logging provided by ASP.NET Core. This provides an ILogger interface that allows the provider of your choice to be used while minimizing the impact to existing code. Another nice aspect of this is that the code can be used not only in .NET Core on Windows and Linux, but in the full .NET framework too, giving the ability to standardize your instrumentation code across .NET and .NET Core.

How is this supposed to work because when I tried to add the extensions library (to my service fabric cluster application project that compiles to .net framework 4.5.2), it is attempting to bring down all asp.net core related binaries?

Answer

Morten Nørgaard picture Morten Nørgaard · Mar 13, 2018

@LoekD's answer is absolutely correct. Here's a .NET Framework example of how to use the Microsoft Extentions Logging framework with Serilog.

public class Program
{
    private static void Main()
    {
        // instantiate and configure logging. Using serilog here, to log to console and a text-file.
        var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
        var loggerConfig = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        loggerFactory.AddSerilog(loggerConfig);

        // create logger and put it to work.
        var logProvider = loggerFactory.CreateLogger<Program>();
        logProvider.LogDebug("debiggung");

    }
}

Requires Microsoft.Extensions.Logging, Serilog.Extensions.Logging and Serilog.Sinks.File NuGet packages.