Debugging Dataverse Plugins: Trace Logs, Profiler and Application Insights
A practical guide to debugging Dynamics 365 plugins with trace logs, the Plugin Registration Tool profiler, Visual Studio replay and Application Insights.
In Dynamics 365 online you cannot attach a debugger to the server where your plugin runs. Plugins execute in a sandbox in Microsoft's cloud, often in milliseconds, triggered by users, flows or integrations. When something goes wrong, you need other ways to see what happened.
This guide covers the four tools every Dataverse developer should master: the plugin trace log, the Plugin Registration Tool profiler, replay debugging in Visual Studio and Application Insights. It also shares a practical approach to tracking down the most common plugin bugs, a reusable base class, and answers to the questions developers ask most often.
The debugging toolbox at a glance
| Tool | Best for | Where |
|---|---|---|
| Plugin trace log | Seeing what your code did in any environment | Dataverse (Plug-in Trace Log table) |
| Plugin profiler + replay | Stepping through real executions line by line | Plugin Registration Tool + Visual Studio |
| Application Insights | Trends, failures and performance over time | Azure |
| Unit tests (e.g. FakeXrmEasy) | Reproducing logic without an environment | Your test project |
1. The plugin trace log
Turn it on
- In the environment, open Settings → Administration → System Settings (or the Power Platform admin center environment settings).
- On the Customization tab, set Enable logging to plug-in trace log to:
- Off: no logs
- Exception: logs only when a plugin throws an exception (good default for production)
- All: logs every execution (use temporarily for troubleshooting; it creates many records)
Write useful trace messages
Use ITracingService from the service provider:
public void Execute(IServiceProvider serviceProvider)
{
var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
tracing.Trace($"Message: {context.MessageName}, Stage: {context.Stage}, Depth: {context.Depth}");
tracing.Trace($"Entity: {context.PrimaryEntityName}, Id: {context.PrimaryEntityId}");
try
{
// business logic
tracing.Trace("Step 1: validated input");
// ...
}
catch (Exception ex)
{
tracing.Trace($"Error: {ex}");
throw new InvalidPluginExecutionException("Unable to process the request. Please contact support.", ex);
}
}
What to trace:
- message, stage, mode and depth
- important IDs and decision points ("discount above limit, creating approval task")
- timings around slow operations
- values of key fields (avoid personal or sensitive data)
Read the logs
Open Advanced Find or the maker portal and query the Plug-in Trace Log table, or use XrmToolBox's Plugin Trace Viewer, which makes filtering by plugin, message, date and exception much easier.
Each log includes the type name, message, entity, execution start time, duration, depth, correlation ID, your trace messages and exception details.
Tips
- Trace output is limited in size per execution, so keep messages concise.
- Synchronous plugins that throw an exception roll back the transaction, but the trace log is still written when logging is on.
- Use the correlation ID to link plugins that ran in the same operation chain.
- Trace logs are deleted automatically after a retention period, so export important logs if you need them for later analysis.
2. Plugin Registration Tool profiler
The profiler captures the full execution context of a real plugin run so you can replay it locally.
Install the profiler
- Open the Plugin Registration Tool (installed via the Power Platform CLI with
pac tool prt, or from NuGet). - Connect to your development or test environment.
- Click Install Profiler.
Profile a step
- Select the plugin step you want to debug.
- Click Start Profiling.
- Choose to save the profile as an exception (the user sees an error and can download the profile) or persist to entity (the profile is stored in Dataverse without interrupting the user). Persisting is usually more convenient.
- Reproduce the scenario in the app, such as updating the record.
Replay in Visual Studio
- Open the plugin project in Visual Studio and build in Debug mode so the assembly matches the registered one.
- In the Plugin Registration Tool, click Debug (Replay Plug-in Execution).
- Select the saved profile and your local plugin assembly.
- In Visual Studio, Attach to Process and select the Plugin Registration Tool process.
- Set breakpoints and click Start Execution in the tool.
You can now step through your code with the real input parameters, images and context.
Important: replay uses a copy of the original context. Service calls in replay may run against the connected environment, so use non-production environments.
When you're done
- Stop profiling on the step.
- Uninstall the profiler from production-like environments when not in use.
3. Application Insights
For production systems, you need visibility over time, not just single executions.
Export Dataverse telemetry
In the Power Platform admin center, you can set up data export to Application Insights for an environment. This sends Dataverse telemetry, including plugin executions, API calls and failures, to Azure.
Log from your plugin with ILogger
Dataverse supports an ILogger in plugins that writes to Application Insights when telemetry export is configured:
var logger = (ILogger)serviceProvider.GetService(typeof(ILogger));
logger.LogInformation("Order {OrderId} processed in {Ms} ms", orderId, elapsed);
logger.LogWarning("Credit limit exceeded for account {AccountId}", accountId);
Useful queries
In Application Insights, use Kusto queries to find:
- the slowest plugins by average and 95th percentile duration
- plugins with the most failures in the last 7 days
- errors correlated with specific users or times
dependencies
| where type == "Plugin"
| summarize avg(duration), percentile(duration, 95), count() by name
| order by percentile_duration_95 desc
The exact table names and fields depend on your telemetry setup, so adjust the query to your schema.
Alerts
Create Azure Monitor alerts for spikes in plugin failures or durations, so your team hears about problems before users raise tickets.
4. Unit tests
Many plugin bugs can be found before deployment. Frameworks such as FakeXrmEasy simulate the Dataverse context in memory:
- create a fake context with test records
- execute your plugin with a target entity and images
- assert the records created or updated
Tests are fast, repeatable and run in your build pipeline. They are especially valuable for complex business rules.
A reusable base class for debuggable plugins
Most mature Dynamics 365 projects use a base class so every plugin traces in the same way. A simple version:
public abstract class PluginBase : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = factory.CreateOrganizationService(context.UserId);
var sw = System.Diagnostics.Stopwatch.StartNew();
tracing.Trace($"{GetType().Name} | {context.MessageName} | Stage {context.Stage} | Depth {context.Depth}");
try
{
ExecutePlugin(context, service, tracing);
}
catch (InvalidPluginExecutionException) { throw; }
catch (Exception ex)
{
tracing.Trace(ex.ToString());
throw new InvalidPluginExecutionException($"An unexpected error occurred in {GetType().Name}.", ex);
}
finally
{
tracing.Trace($"Completed in {sw.ElapsedMilliseconds} ms");
}
}
protected abstract void ExecutePlugin(IPluginExecutionContext context, IOrganizationService service, ITracingService tracing);
}
Every plugin then inherits from PluginBase, and you get consistent start, end, timing and error information in the trace log without repeating code.
A practical debugging process
When a user reports "I get an error when saving a contract":
- Get the error details. Ask for a screenshot and the downloaded log file from the error dialog. Note the time.
- Check the trace log. Filter by the time and entity. Find the plugin, the exception and your trace messages.
- Identify the trigger. Check message, stage, depth and the initiating user. Was it a user, a flow or an integration?
- Reproduce in dev. Use the same data if possible. If not obvious, profile the step and replay it in Visual Studio.
- Fix and add tests. Write a unit test that reproduces the bug, then fix the code.
- Improve tracing. If the logs didn't help, add better trace messages before the next release.
Common plugin bugs and how to spot them
1. NullReferenceException
Usually a column not included in the target (only changed columns are present in update targets) or a missing image. Use entity.Contains("field") or GetAttributeValue<T>(), and register pre/post images.
2. Infinite loops
The error mentions the maximum depth. Trace context.Depth, add filtering attributes, and avoid updating the triggering columns.
3. "Generic SQL error" or deadlocks Often long-running synchronous plugins or concurrent updates to the same records. Shorten transactions, move work to async, and avoid unnecessary updates.
4. Timeouts The plugin runs longer than the 2-minute sandbox limit. Trace timings, optimise queries and offload heavy work (see our plugin timeout guide).
5. Works for admin, fails for users The plugin runs in the calling user's context by default. Check security roles, or run specific operations with a system or dedicated user service where appropriate.
6. Different behaviour in production Check plugin step registration (filtering attributes, images, execution order), solution layers, and configuration data that differs between environments.
Frequently asked questions
Can I debug a plugin directly in Dynamics 365 online with breakpoints? Not on the server itself. Use the profiler to capture a real execution and replay it in Visual Studio, which gives you the same breakpoint experience with real data.
Why is my trace log empty?
Check that trace logging is set to Exception or All, that your code actually calls tracing.Trace(), and that the plugin really ran (check the step is enabled and filtering attributes match the changed fields).
Do trace logs affect performance? Logging every execution with All creates many records and adds some overhead, so use it temporarily. Exception is a good production setting.
Can I see traces for asynchronous plugins? Yes. Traces for async plugins appear in the trace log, and the related System Job record also shows the error message for failed async executions.
What about custom workflow activities and custom APIs? They use the same tracing service and appear in the trace log, so the same techniques apply.
Is the profiler safe for production? Use it only when there is no other option, for a short time and on a specific step. Remove it afterwards to avoid overhead and confusion.
Best practices for debuggable plugins
- Trace at decision points, not every line.
- Throw
InvalidPluginExecutionExceptionwith user-friendly messages; log technical details in traces. - Keep plugins small and focused; one responsibility per plugin.
- Use a base plugin class that sets up tracing, context and timing consistently.
- Set trace logging to Exception in production by default.
- Monitor with Application Insights and set up alerts for failure spikes.
- Never debug in production with the profiler unless absolutely necessary, and remove it afterwards.
How Zyppro can help
Zyppro Technologies develops and troubleshoots Dynamics 365 and Dataverse plugins, custom APIs and integrations. Our developers can review your code, set up tracing and monitoring, and fix production issues quickly. We also provide live job support for developers who need an expert alongside them.
Visit www.zyppro.com or email contact@zyppro.com.