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). And depends on the scenario that you need, you can log the information anywhere your want. In this blog post, you will learn how I implement it in Console.

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

Throw an error on plugin

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

You need to create an console app that install DataverseServiceClient. Then here 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!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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