Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I integrate NLog with MvvmCross using Microsoft.Extensions.Logging


How do I integrate NLog with MvvmCross using Microsoft.Extensions.Logging


Integrating NLog with MvvmCross using Microsoft.Extensions.Logging involves several steps. MvvmCross, starting from version 8, uses Microsoft.Extensions.Logging for its logging infrastructure, which allows you to easily integrate third-party logging providers like NLog.

Step 1: Install Required NuGet Packages

First, you need to install the necessary NuGet packages in your project. You will need `NLog.Extensions.Logging` and `NLog`. If your project is an ASP.NET Core application, consider using `NLog.Web.AspNetCore` instead.

bash
Install-Package NLog.Extensions.Logging
Install-Package NLog

Step 2: Configure NLog

You need to configure NLog to work with your application. This typically involves creating an `nlog.config` file or configuring it through `appsettings.json` if you prefer to manage configurations in a single place.

Using `nlog.config`:

Create an `nlog.config` file in the root of your project and configure your targets and rules. Here's a simple example:

xml



  
    
  

  
    
  

Using `appsettings.json`:

If you prefer to manage your NLog configuration through `appsettings.json`, you can do so by adding the following configuration:

json
{
  "NLog": {
    "targets": {
      "f": {
        "type": "FileTarget",
        "fileName": "${basedir}/logs/${shortdate}.log"
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Info",
        "writeTo": "f"
      }
    ]
  }
}

Step 3: Integrate NLog with Microsoft.Extensions.Logging

In your MvvmCross setup, you need to configure the logging infrastructure to use NLog. This involves implementing `ILoggerProvider` and `ILoggerFactory` interfaces or simply using the `AddNLog` method provided by `NLog.Extensions.Logging`.

Here's how you can do it in your `MvxSetup` class:

csharp
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;

public class Setup : MvxSetup
{
    protected override void InitializeFirstChance()
    {
        base.InitializeFirstChance();

        // Register NLog as the logging provider
        var services = new ServiceCollection();
        services.AddLogging(loggingBuilder => loggingBuilder.ClearProviders().AddNLog());
        var serviceProvider = services.BuildServiceProvider();

        // You can now inject ILogger into your classes
    }
}

However, for MvvmCross, you typically need to provide implementations for `ILoggerProvider` and `ILoggerFactory`. Here's a more detailed approach:

1. Implement `ILoggerProvider` and `ILoggerFactory`:**

You can create a custom provider that wraps NLog's functionality. However, since `NLog.Extensions.Logging` already provides an integration with Microsoft.Extensions.Logging, you can use it directly.

2. Register NLog in MvvmCross IoC:**

Instead of manually implementing providers, you can leverage the existing integration by registering NLog through the MvvmCross IoC container.

csharp
   protected override void InitializeFirstChance()
   {
       base.InitializeFirstChance();

       // Register NLog as the logging provider
       var services = new ServiceCollection();
       services.AddLogging(loggingBuilder => loggingBuilder.ClearProviders().AddNLog());
       var serviceProvider = services.BuildServiceProvider();

       // Register the logger factory with MvvmCross IoC
       Mvx.RegisterSingleton(serviceProvider.GetService());
   }
   

Step 4: Use Logging in Your Application

Now that NLog is integrated with MvvmCross using Microsoft.Extensions.Logging, you can inject `ILogger` into your view models or services and use it for logging.

csharp
public class MyViewModel : MvxViewModel
{
    private readonly ILogger _logger;

    public MyViewModel(ILogger logger)
    {
        _logger = logger;
    }

    public void SomeMethod()
    {
        _logger.LogInformation("Hello, World!");
    }
}

This setup allows you to leverage the powerful features of NLog, such as structured logging and multiple targets, within your MvvmCross application.

Citations:
[1] https://www.nuget.org/packages/NLog.Extensions.Logging/5.3.2
[2] https://nlog-project.org
[3] https://stackoverflow.com/questions/63169570/xamarin-mvvmcross-how-to-use-nlog-for-imvxlogprovider
[4] https://www.mvvmcross.com/documentation/fundamentals/logging-new
[5] https://www.nuget.org/packages/NLog.Extensions.Logging/5.0.0
[6] https://learn.microsoft.com/en-us/dotnet/core/extensions/logging
[7] https://www.nuget.org/packages/NLog.Extensions.Logging
[8] https://nlog-project.org/2021/08/25/nlog-5-0-preview1-ready.html