web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Suggested Answer

Write D365 custom plugin trace logs to application insights

(4) ShareShare
ReportReport
Posted on by 10
Hi All,
 
I have been trying to figure out how to write trace messages from my customs plugins to Application Insights, I know there is a OOB feature to export the data to Application Insights but this option is not available to me because I don't have the Admin role. I still want to write logs from a few plugins. I am new to Dynamics 365, Can anyone point me to the right direction? I have searched for blogs/documentation but couldn't find anything. Post here as a last resort.
I have the same question (0)
  • Suggested answer
    Holly Huffman Profile Picture
    6,532 Super User 2025 Season 2 on at

    Hi there! Good morning, evening, or afternoon - depending on where you are :) Hope you are well today! 

    Here’s an approach you can take:
    • Set Up Application Insights Instrumentation Key in Your Code:
      • First, obtain the Instrumentation Key for your Application Insights instance
        • If you don’t have access to it, you may need to collaborate with an admin or team member who has.
      • In your plugin code, you’ll manually log messages to Application Insights by making use of the Application Insights Telemetry SDK.
    • Add Application Insights Telemetry SDK:
      • Install the Microsoft.ApplicationInsights NuGet package in your plugin project.
      • Use the TelemetryClient class to send trace messages and telemetry data to Application Insights.
        Here’s a code snippet to help:


        using Microsoft.ApplicationInsights;
        using Microsoft.ApplicationInsights.Extensibility;

        public class CustomPlugin : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                var telemetryConfig = TelemetryConfiguration.CreateDefault();
                telemetryConfig.InstrumentationKey = "YOUR_INSTRUMENTATION_KEY";
                var telemetryClient = new TelemetryClient(telemetryConfig);

        telemetryClient.TrackTrace("This is a custom trace message from my plugin.");
                telemetryClient.Flush();
            }
        }
      • Replace "YOUR_INSTRUMENTATION_KEY" with the actual key for your Application Insights.
    • Deploy and Test Your Plugin:
      • Once the above changes are made, deploy the plugin to your Dynamics 365 environment.
      • Perform operations that trigger the plugin and confirm that trace messages appear in Application Insights.
    • Considerations for Logging:
      • Avoid over-logging to prevent clutter in Application Insights and unnecessary costs.
      • Implement error handling to ensure that your plugin performs well, even if Application Insights connectivity fails.
    • Alternative Tools:
      • If Application Insights access remains a challenge, you might also consider other logging mechanisms, such as writing trace messages to the Plugin Trace Log in Dynamics 365.
  • LongmontPotionCastle Profile Picture
    10 on at
    @Holly Huffman, I tried this but I get the following error as soon as my plugin triggers - Exception Message: Could not load file or assembly 'Microsoft.ApplicationInsights, Version=2.23.0.29, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040).
     
  • Suggested answer
    CU13031143-0 Profile Picture
    42 on at
    Hi,
     
    If you’re unable to use Application Insights directly within your plugin, here are alternative approaches to capture and analyze plugin logs outside of Dynamics 365.
     
    Alternative Solutions for Capturing Plugin Logs
     
    1. Log to a Custom Entity in Dataverse
     
    Instead of sending logs to Application Insights, you can create a custom entity in Dataverse (e.g., Plugin Log) and write log records directly from your plugin.
     
    How It Works:
     
    Create a custom entity (Plugin Log) with fields like Message, Severity, Timestamp, Plugin Name, and Error Details.
     
    Modify your plugin to create records in this entity whenever you need to log data.
     
     
    Example Code:
     
    public class LogToDataversePlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
     
            try
            {
                tracingService.Trace("LogToDataversePlugin: Execution started.");
     
                Entity logEntry = new Entity("new_pluginlog");
                logEntry["new_message"] = "Execution started";
                logEntry["new_pluginname"] = "LogToDataversePlugin";
                logEntry["new_severity"] = "Information";
                logEntry["new_timestamp"] = DateTime.UtcNow;
     
                service.Create(logEntry);
            }
            catch (Exception ex)
            {
                tracingService.Trace("Error: {0}", ex.Message);
     
                Entity errorLog = new Entity("new_pluginlog");
                errorLog["new_message"] = ex.Message;
                errorLog["new_pluginname"] = "LogToDataversePlugin";
                errorLog["new_severity"] = "Error";
                errorLog["new_timestamp"] = DateTime.UtcNow;
     
                service.Create(errorLog);
     
                throw;
            }
        }
    }
     
     
    2. Use Azure Service Bus for Logging
     
    If you can’t use Application Insights but have access to Azure Service Bus, you can push log messages to a Service Bus queue, which can then be processed by an external service (like an Azure Function or Power Automate flow).
     
    How It Works:
     
    The plugin sends log messages to a Service Bus queue.
     
    An external Azure Function or Power Automate flow reads and stores the logs in a central location like Azure Table Storage, a database, or Application Insights.
     
     
    Example Code:
     
    using Microsoft.Azure.ServiceBus;
    using System.Text;
    using System.Threading.Tasks;
     
    public class LogToServiceBusPlugin : IPlugin
    {
        private const string ServiceBusConnectionString = "Endpoint=sb://yournamespace.servicebus.windows.net/;SharedAccessKeyName=YourKey;SharedAccessKey=YourValue";
        private const string QueueName = "pluginlogs";
        private static IQueueClient queueClient;
     
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
     
            try
            {
                tracingService.Trace("LogToServiceBusPlugin: Execution started.");
                SendMessageToQueue("Plugin executed successfully", "Information").Wait();
            }
            catch (Exception ex)
            {
                tracingService.Trace("Error: {0}", ex.Message);
                SendMessageToQueue(ex.Message, "Error").Wait();
                throw;
            }
        }
     
        private static async Task SendMessageToQueue(string message, string severity)
        {
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
            string logEntry = $"{{ \"message\": \"{message}\", \"severity\": \"{severity}\", \"timestamp\": \"{DateTime.UtcNow}\" }}";
            Message busMessage = new Message(Encoding.UTF8.GetBytes(logEntry));
            await queueClient.SendAsync(busMessage);
            await queueClient.CloseAsync();
        }
    }
     
    3. Send Logs to an External API or Database
     
    If your organization has an existing logging service or database, your plugin can send log messages there using an HTTP request or direct database write.
     
    Example Approaches:
     
    REST API: Send logs to an external web service using HttpClient.
     
    SQL Database: Use SqlConnection to write logs to a central database.
     
    Logging Service: Integrate with tools like Splunk, Log Analytics, or Serilog.
     
     
    Example: Sending Logs via HTTP Request
     
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
     
    public class LogToExternalApiPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
     
            try
            {
                tracingService.Trace("LogToExternalApiPlugin: Execution started.");
                SendLogToApi("Execution started", "Information").Wait();
            }
            catch (Exception ex)
            {
                tracingService.Trace("Error: {0}", ex.Message);
                SendLogToApi(ex.Message, "Error").Wait();
                throw;
            }
        }
     
        private static async Task SendLogToApi(string message, string severity)
        {
            using (HttpClient client = new HttpClient())
            {
                string apiUrl = "https://yourloggingapi.com/logs";
                string jsonPayload = $"{{ \"message\": \"{message}\", \"severity\": \"{severity}\", \"timestamp\": \"{DateTime.UtcNow}\" }}";
                var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
     
                await client.PostAsync(apiUrl, content);
            }
        }
    }
     
     
    If you don’t have access to Azure services, Dataverse logging is the easiest alternative. If you need real-time log processing, Service Bus or an external API would be better options.
     
    Hope this helps! Let me know if you have any questions.
     
    Best,
    Nikhil Sarpatwari 
     
    If you found my comment helpful or if this resolves your issue, please acknowledge it by liking the comment or letting me know. Thanks for helping keep the community engaged!
     

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Martin Dráb Profile Picture

Martin Dráb 47 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 38 Super User 2025 Season 2

#3
Pallavi Phade Profile Picture

Pallavi Phade 32

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans