Enable Log instantly by passing ILogger in DataverseServiceClient

When you are using DataverseServiceClient, we can see the constructor where we can pass an instance of ILogger. The purpose of this, of course, is to get more information regarding what is happening in our system (you also can monitor the performance). Depending on the scenario that you need, you can log the information anywhere you want. In this blog post, you will learn how I implement it in the Console.

For testing purposes, I wrote a plugin that will throw an error like the below code:

Throw an error on the plugin

Then I register the plugin and add the plugin step to the Contact entity:

You need to create a console app that installs DataverseServiceClient. Then there is my code:

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Extensions.Logging;
using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

var connectionString =
    "AuthType=OAuth;Username=xxx;Password=xxx;Url=https://xxx.crm.dynamics.com/;AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97";

var index = 0;

var client = new ServiceClient(connectionString, new ConsoleLogger());
do
{
    client.Execute(new WhoAmIRequest());

    client.Retrieve("contact", new Guid("877036e2-0f05-ed11-82e4-00224805a8e0"), new ColumnSet(true));

    try
    {
        var entity = new Entity("contact", new Guid("877036e2-0f05-ed11-82e4-00224805a8e0"));
        entity["firstname"] = "Temmy";
        client.Update(entity);
    }
    catch
    {
        //ignore
    }
   
    index++;
} while (index<5);


Console.WriteLine("Done update");

internal class ConsoleLogger : ILogger
{
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
    {
        Console.WriteLine($"[{DateTime.Now}] {logLevel} {state.ToString()}");
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        throw new NotImplementedException();
    }
}

Below is the result:

Result

Happy CRM-ing!

Author: temmyraharjo

Microsoft Dynamics 365 Technical Consultant, KL Power Platform User Community Leader, Student Forever, Test Driven Development, and Human Code enthusiast.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.