Showing posts with label AppInsights. Show all posts
Showing posts with label AppInsights. Show all posts

Monday 28 August 2023

App Insights for Power Platform - Part 10 - Custom Connector Logging Thoughts

Overview: One of our developers was asking about a log he was struggling to trace, and it took me awhile and a lot of help from the community to truly understand the issue.  My scenario is shown below:


Scenario: I have a Dataverse change triggering a flow, the flow calls a Custom Connector, that in turn calls an Azure Function (that I control).  So the flow fails, and I have used a pattern in the flow to catch the error and log it into Log Analytics.  All good, then I don't see the event where the action calls the function, my function has logging enabled.  I can see I am getting a 401 unauthorized error.  

Initial Hypothesis: The Power Platform use APIM internally to implement Custom Connectors, and there is no access for clients/tenants to see the internal logging/traffic.  Microsoft have provide the ability to use iLogger on the custom connector to log the traffic.  

We have flows that intermittently get a 401, when the flow is manually rerun, the flow works and I can see the traffic coming into the Function.

The failure rate is extremely low and retries almost always fix the issue, and a third try always ensures the transaction goes thru.

Resolution:  Add logging to the custom connector so we can speak with MS support about the issue.  Add alerting to notify support, they can contact the user or chose to rerun the flow. 

Alternative: If I  enable the code, I can override the behaviour and inject C# code to work with the backend, or handle logic such as replacing text,... 

1. In step "4. Code" tab of the custom connector, add the code below:

You can do any C# logic, I'm sending the original request thru and if it doesn't return me a 200, I'm logging it as critical. 

2. Update the connector, go to the next step "5. Test" > "Update Connector" (Tip: follow the steps)

3. Run the "Test operation", open the Response and validate the response body is correct, then open the "Code logs" tab.  If it is blank, re-run the "Update Connector" (irritating but true). 

304 return from the API, which is cached and not a problem, but 400, 500 would be an issue, could also look out for 429s.

Full C# Code:

public class Script : ScriptBase

{

    public override async Task<HttpResponseMessage> ExecuteAsync()

    {       

        this.Context.Request.Method = HttpMethod.Get;

        HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(continueOnCapturedContext: false);

        Context.Logger.LogTrace("Custom Connector ListBooks called "); 

        if (response.StatusCode == HttpStatusCode.OK)

        {    Context.Logger.LogTrace("Success");      }   

        {    Context.Logger.LogCritical("Critical | " + response);     }

        return response;

    }

}

More Info:

https://learn.microsoft.com/en-us/connectors/custom-connectors/write-code (NB)

https://never-stop-learning.de/logging-in-custom-connector-code/ (NB) The 2nd part of this post on the Alternative , is a rehash of this amazing post - I amended the logic and now I'm wondering is I could write to App Insights using the SDK?

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging (this post)

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern


Friday 11 August 2023

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key) (this post)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

Overview: Logging & monitoring for Canvas apps is done in two parts: App Insights, and using the Canvas app Monitor.  This post focuses on logging via App Insights.


Note: Once a solution that contains a Instrumentation key, they app logging key cannot be alter unless you make the environment have unmanaged layers.  You can use PowerCli and compose a new managed solution for each DTAP environment but it's a new compile for each environment.

Example:

In the annotated diagram below including a log snippet.  

1. Canvas App has an instrumentation key, the log captures the front end action

2. Calls to Dataverse & Power automate Flows are logged (relies on step 1)

3. Custom connector is calling an Azure Function (Function is logging to Log Analytics or app Insights),

4. the function logs into APIM and sends APIM a request (APIM logging is setup on the end points), and

5. APIM sends an outbound API request and captures the response (relies on step 4)

Note in this example I have Correlation tracking enabled on the Canvas App to get the full timeline, as shown below, it has been an experimental feature for a few years now.


When I turn off the Correlation, it is not as easy to trace items from start to finish.  All I get by default is the steps 3&4 data in my transaction search timeline.

All 5 pieces are still captured but the timeline has to be pieced together for tracing.


I would also enable the preview feature for logging as well as the experimental if the clients governance allows experimental features to be turned on.

Summary: Always add as many logging features as possible in Canvas Apps, think about where your logs go and also setup logging on Azure services to transaction can be traced.

Sunday 18 June 2023

App Insights for Power Platform - Part 6 - Power Automate Logging

Note: Announcement 23 Aug 2023 - integration of Power Automate telemetry data with Azure Application Insights.

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging (this post)

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

Overview:
  • Power Automate holds it own set of logs and history.  While Power Automate's internal logging is good and useful, it does not push logs into App Insights or Log Analytics for central monitoring.
  • You can manually export Power Automate logs from Power Platform and import them into Log Analytics, using the "Data Export" option.

  • Or you can create an Azure Functions that you can use to write to App Insights, below is a simple recording of the function (this is recording aims to remove complexity so there is no VS Code or publishing.
Function to write into App Insights Logs

#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    int eventId = data?.eventId;
    string errType = data?.errType;
    string errMsg = data?.errMsg;
    string correlationId = data?.correlationId;
    string workflowId = data?.workflowId;
    string workflowUrl = data?.workflowUrl;    
    string flowDisplayName = data?.flowDisplayName;

var custProps = new Dictionary<stringobject>()
{
    { "CorrelationId", correlationId},
    { "WorkflowId", workflowId},
    { "WorkflowUrl", workflowUrl},
    { "WorkflowDisplayName", flowDisplayName}
};

using (log.BeginScope(custProps))
{
    if (errType=="Debug"
    {
        log.Log(LogLevel.Debug, eventId, $"{errMsg}");   
    }
    else if (errType=="Critical")
    {
        log.Log(LogLevel.Critical, eventId, $"{errMsg}");  
    }
    else if (errType=="Warning")
    {
        log.Log(LogLevel.Warning, eventId, $"{errMsg}");   
    }
    else if (errType=="Trace")
    {
        log.Log(LogLevel.Trace, eventId, $"{errMsg}");          
    }
    else if (errType=="Error")
    {
        log.Log(LogLevel.Error, eventId, $"{errMsg}");          
    }
    else
    {        
      log.LogInformation($"Event is {eventId}, type is {errType}, and msg is {errMsg}");
    }        
};
    string responseMessage = $"This HTTP triggered function executed successfully. {errType} - {errMsg}";
    return new OkObjectResult(responseMessage);
}

Power Platform Admin Centre:

There is nice analytics inside the Power platform Admin Centre as shown below to examine Flows/Power automate:

The flows can also be reviewed on a per environment basis:

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging (this post)

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

Monday 12 June 2023

App Insights for Power Platform - Part 5 - Logging for APIM

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM (this post)

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

Overview: APIM is often part of you Power Platform solutions, such as monitoring and controlling all inbound and outbound traffic or to wrap over Azure functions.

Within APIM you can add multiple App Insights Instances.  You can send all logging to a single instance an override specific API's to log to different instances.  Making the logging nice and granular.

Setup Logging

The diagram below is where i used the operation Parent Id to find a log entry using the Transaction Logs in App Insights I can see the APIM entry and the entry to the backend 3rd party and their http response
You can hook up so you can see the Canvas App Session, then the function call, which calls APIM, and then see the backend call to the gov 3rd party API.

  1. Logging can be global or set at the API level in APIM.
  2. Telemetry "Sampling" will log a percentage of requests.
  3. "Always log errors" captures any errors APIM gets.
  4. Headers and body are not included in logs unless you specify them.

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM (this post)

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

Friday 9 June 2023

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics

Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics  (this post)

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

 There are two ways to setup App Insights:

  1. Classical approach (soon to be removed), and
  2. The Version 2 approach also refereed to as the workspace based app Insights approach.

Image1. The Version 2/Workspace-based App Insights approach stores all new logs in Log Analytics storage.

More: Using App Insights using "version 2".  The original app insights stored it's logs within itself, this is sometimes refereed to as "classic app insights".  Classic App Insights is being deprecated so version 2 is compulsory from early 2024.  "Version 2" stores App Insights Logs in a workspace (Azure Log Analytics).

We need all our service i.e. Canvas apps, Dataverse, Power Automate, APIM, ESB, Key Vault, Azure Functions to store operation logs in App Insights workspace based approach.  We shall discuss Canvas App Logging in <App Insights for Power Platform - Part 3 - Canvas App Logging>.

Note: Operations logged to app insights store under the hood consist of 3 parts: 

1. App Id to log to

2. Content to put into the Log analytics for full logging

3. Metric data.

Setup App Insights

Open The Azure Portal.

In your subscription, you need a resource group and storage, go and add the log analytics and the app insights.

Setup the Log Analytics instance to connect the App Insights instance too.  The free tier is normally sufficient for demo purposes.

Setup App Insights using a Workspace/Log Analytics, and pls name your resources properly.

View your logs

App Insights is integrated well with all Azure services and are easily accessible.  We will go into the AppInsights Blade and look at the Logs, I added this query that will look for all logs and ordered them to show the latest first.

Note: The logs are stored in Log analytics.  To view the logs you can either use App Insights or Log analytics and the syntax is slightly different, see the image below:

Terminology Worth Understanding:

App Insights stores data in Log Analytics, you can read/write thru App Insights or Log analytics.  There is also Azure Metrics.  All of these services fall under the umbrella term of Azure Monitor.  When writing to the logs, the data is made up of 3 parts. 1, identifier for the log 2, Log analytics data that can be queried and 3, metric data. 

APIM Monitoring & Logging via Portal:

Sample Kusto Queries:

// Function used to call APIM

dependencies 

| where cloud_RoleName == "azure-func-name-01"

| where type  == "HTTP"

| where target !contains "login"

| order by timestamp desc 

// Check Outbound APIM 

requests 

| where cloud_RoleName == "devapim North Europe"

| order by timestamp desc 

// Backend data is in the customDimensions logged by APIM

dependencies   

| where type == "Backend"

| order by timestamp desc 

| extend req = tostring(customDimensions["Request-Body"])

//| project  timestamp, id, req

| where req contains "BJ69 TFF"

// Retrieve Canvas app data based on customDimensions logged 

pageViews

| extend 

    AppName = tostring(customDimensions["ms-appName"]),

       Env = tostring(customDimensions["ms-environmentId"]),

    LastSuccess = datetime_diff('minute', now(), timestamp)

| where AppName == "Bus Revenue Inspection"

| summarize by Env 

//| summarize arg_max(timestamp, *), Count = count() by AppName

//| order by LastSuccess desc

//| project LastSuccess, NoOfPageViews = Count


Example querying Azure Log Analytics for Traces I raised from a Canvas App

// KQL syntax varies slightly when querying the Log analtics rather than App Insights. 

AppTraces

| where Message contains "App Loaded with Events issue - Compliance Subject"

| extend 

    AppName = tostring(Properties["ms-appName"]),

    Env = tostring(Properties["myappEnvironment"]) // Properties is used instead of customDimensions

| order by TimeGenerated desc


Series

App Insights for Power Platform - Part 1 - Series Overview 

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics (this post)

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM 

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power Automate Licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

App Insights for Power Platform - Part 1 - Series Overview

Overview: Microsoft have great capabilities for logging and monitoring.  In this series of posts I will be examining the various parts of logging that may be useful in building solutions that are well monitored, provide alerting, easy tracing, and identifies issues or potential issues as soon as possible.

I am looking at App Insights for Power Platform monitoring.  So this includes: 

  • Power Apps (Canvas, and model apps),
  • Power Automate,
  • APIM, 
  • Azure Functions, 
  • Azure Service Bus, and
  • App Insights.

I shall be setting up a demo environment and these are the logical components being covered.


All the components making up the solution shall log into Log Analytics (left-hand side of the diagram).

For Continuous Integration, my clients will be Postman monitor (it's awesome and so easy to use all those postman collections), DevOps is great and I'll use it to run smoke tests after new releases.  I also use flows, to report on flows (sounds nuts but i love it).  These are at the bottom of the diagram. 

Lastly on the right of the diagram, I look at extracting logs for reporting (Power BI), and Monitoring using Azure DevOps (p.s. think about Grafana instead of DevOps Dashboards, it so nice).

Couple of extras are: Availability Logging, alerting, automating Canvas app testing, Playwright.  

From the diagram, you can see the data is now held in Log analytics and it can be queried via Log Analytics or App Insights using Kusto.  Note: the syntax is slightly different.

Series

App Insights for Power Platform - Part 1 - Series Overview (this post)

App Insights for Power Platform - Part 2 - App Insights and Azure Log Analytics 

App Insights for Power Platform - Part 3 - Canvas App Logging (Instrumentation key)

App Insights for Power Platform - Part 4 - Model App Logging

App Insights for Power Platform - Part 5 - Logging for APIM (this post)

App Insights for Power Platform - Part 6 - Power Automate Logging

App Insights for Power Platform - Part 7 - Monitoring Azure Dashboards 

App Insights for Power Platform - Part 8 - Verify logging is going to the correct Log analytics

App Insights for Power Platform - Part 9 - Power automate licencing

App Insights for Power Platform - Part 10 - Custom Connector enable logging

App Insights for Power Platform - Part 11 - Custom Connector Behaviour from Canvas Apps Concern

Tip: The Power Platform Admin Centre has a good overview of the Power Platform, but to make logging and monitoring better push data into Azure Log analytics and monitor and alert centrally.

Also seeView and download Dataverse analytics - Power Platform | Microsoft Learn

Friday 19 May 2023

Logging and Monitoring Advanced Canvas Apps

Overview: Most Canvas apps reach back to 3rd parties or internal storage e.g. SQL, Dataverse, blobs to persist data.  In an ideal world we want to be able to identify error and performance concerns and be able to trace quickly.

Scenario: A canvas app performs a search against a custom connector, that goes to an external API, for example search's for Company Numbers from an Open API.

  • The annotated diagram, in orange records the button pressed to run the search.  This only shows if the "Upcoming feature", "Enable Azure Application Insights correlation tracing" is enabled.
  • A custom connector, in blue, makes  a call to an REST/Open API.
  • The last call is to an external API, highlighted in purple, (in this case it was actually a mocked APIM endpoint, but the icon would change it it was totally external such as call API search to the IRS, HMRC, Inland Revenue.

Tip: Always create App Insight Instances using a workspace and not the classic-mode app insights as it is being deprecated by Microsoft in early 2024.

App Insights Understanding:

App Insights setup using the Workspace-based setup (Log Analytics) can be queried in two ways:

  • Query thru App Insights
  • Query thru the Log Analytics workspace (the Kusto/KQL is slightly different, but it's rather minor)

Tip: If you upgrade from classic to the workspace base app Insights, the log history is still "query-able" as App Insights combines the logs from AppInsights Classic (stored in app insights directly) and the logs stored in Log Analytics.

Tip: Power Automate has a connector to Log Analytics so it's good to use this for flows so you can trace canvas apps using flow journeys.  Most people tend to build a custom connector to a function that uses the AppInsights SDK.  I've used both and they are both valid approaches and shown in the annotated diagram below.

The two options for logging Flows into App Insights.

Note: If you create a new App Insights workspace-based instance remember to update the loggers in all you Azure Services to the new instance (app key).  For example functions, APIM and Service Bus are common components.

Note: You can log to multiple workspace/app insights in a tenant and the correlations will be retrieved so you see the full history, assuming you have permissions to all log sources.

Learning: the instrumentation key for app insights has 3 parts to it: 
1) instrumentation key (basically a unique identified to find and allow logs to be saved into AppInsights, 
2) ingestion endpoint (URL for the log), and 
3) monitoring metric endpoint (URL for metrics/performance counters/live metrics/failed requests/). 

Here is an example and you can see the 3 parts:
InstrumentationKey=2675bxxx-xxxb-xxxx-bf5558009ccf;IngestionEndpoint=https://uksouth-1.in.applicationinsights.azure.com/;LiveEndpoint=https://uksouth.livediagnostics.monitor.azure.com/

Thursday 6 April 2023

Runas on Flows

Overview: If I use a connection in a Canvas App, the signed in user uses their own permissions and the connector as as the signed in user.  

Problem: I wish to run a flow as a specific user and not the users calling the flow from the Canvas app.

Hypothesis: I wish to call logging connector into Log Analytics, so I have created a flow, If I use the Power Apps V2 connector, it offers and option to run in another users context.

Resolution: Open the Workflow, ensure you are using the Power Apps V2 trigger, then...


Here I use the Scopes to perform a Try Catch finally set of logic


Tip:  most people tend to use a custom connector to push the error message into a function from the Workflow, the function app uses the App Insights SDK and logs the workflow error.

Simple C# code to write to App Insights using the SDK. 

#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
int eventId = data?.eventId;
string errType = data?.errType;
string errMsg = data?.errMsg;
string correlationId = data?.correlationId;
string workflowId = data?.workflowId;
string workflowUrl = data?.workflowUrl;
string flowDisplayName = data?.flowDisplayName;
var custProps = new Dictionary<string, object>()
{
{ "CorrelationId", correlationId},
{ "WorkflowId", workflowId},
{ "WorkflowUrl", workflowUrl},
{ "WorkflowDisplayName", flowDisplayName}
};
using (log.BeginScope(custProps))
{
if (errType=="Debug") { log.Log(LogLevel.Debug, eventId, $"{errMsg}"); }
else if (errType=="Trace") { log.Log(LogLevel.Trace, eventId, $"{errMsg}"); }
else { log.LogInformation($"Event is {eventId}, type is {errType}, and msg is {errMsg}");}
};
string responseMessage = $"This HTTP triggered function executed successfully. {errType} - {errMsg}";
return new OkObjectResult(responseMessage);
}

More Info:

Reza Dorrani has a great recording showing running Power Automate flows using elevated/shared accounts.

Saturday 18 March 2023

Canvas Apps Workflow logging linkage

Overview:  Power Automate has good monitoring and analysis within the product, and Canvas apps use instrumentation to App Insights and allow for custom tracing.  The issue is linking Canvas app logs to a called workflow.  In this video (2min), I discuss linking Traces in Azure App Insights with flows run on Power Automate.

By passing the the workflow runs workflow back to the calling canvas app, a deep link will allow support to follow a users activity including drilling into the flows being called.



Add additional logging to Azure Log analytics to a custom table within your flows:


Tuesday 14 March 2023

Power Platform Logging, Monitoring, and Alerting

This post relates to a previous strategy blog post, read that first https://www.pbeck.co.uk/2023/02/setting-up-azure-application-insights.html

Overview:  Microsoft uses Azure Application Insights to natively monitor Power Apps using an instrumentation key at the app level.  To log for model driven apps and Dataverse this is a Power Platform config at the environment level e.g. UAT, Prod.

When setting up Application Insights, use the Log Analytics workspace approach and not the "Classic" option as this is being deprecated.

Power Apps (Canvas Apps): Always add the instrumentation key to all canvas apps, it is set in the "App" level within each canvas app.  Deploy solutions brings challenges with changing keys for app insights logging (unmanaged layers).

"Enable correlation tracing" feature imo. should always be turned on, it is still an experimental feature but with it off, the logging is based on a sessionid

"Pass errors to Azure Application Insights" is also an experimental feature.  Consider turning it on.

Canvas Apps have "Monitor", Model driven apps also have this ability to monitor, and Power automate has it's own monitoring

Log to App Insights (put app insights on Azure Log analytics), simple example with customDimensions/record.

Trace("My PB app ... TaxAPI.NinoSearch Error - Search - btnABC",
        TraceSeverity.Error, // use the appropriate tracing level
        {
            myappName: $"PB App: {gblTheme.AppName}",
            myappError: FirstError.Message,  // optional
            myappEnvironment: gblEnv,
            myappErrorCode: 10010,
            myappCorrelationId: GUID() // unique correlationId
        }
    );
Query the logs using kusto:
traces
| extend errCode = tostring(customDimensions["myappErrorCode"]), err = tostring(customDimensions["myappError"])
| where errCode == "100100"

Coming June 2023

Push cloud flow execution data into Application Insights | Microsoft Learn

Allows logging to tie Flows back to the calling Canvas app.  You can now do this manually but it has to be applied at all calls to or after the flow.

Below is a basic checklist of decisions to ensure you have suitable logging

Logging Checklist:

  1. Setup Azure Log Analytics (1 per DTAP env e.g. uat, prd)
  2. Get the workspace key needed for logging to Log analytics "Agents" > "Log Analytics agent instructions", copy the Workspace Id and the Secondary Key
  3. Create an Azure Application Insights per DTAP
  4. Each Canvas app needs an instrumentation key (check, have you aligned DTAP log instances with the Canvas App DTAP)
  5. Power Automate has great monitoring, but it is a good idea to setup logging for Dataverse (which shall cover model apps), done thru Power Platform Admin Studio > Environment
  6. Enable Logging Preview Feature for Canvas apps & check the power automate push cloud execution feature state.
  7. Do you have logging patterns in you Canvas app for errors, do you add tracing, and is it applied consistently?
  8. Do you have a Pattern for Power Automate runs from Canvas apps?  I like to log if the workflow errors after the call.
  9. Do you have a Pattern for Custom Connectors?
  10. Do you correlation trace Custom API (internal and 3rd party)? 
  11. Do you have a Try, Catch, Finally scope/pattern for Workflows.  How do you write to the logs, most common is to use an Azure Function with the C# SDK.  I like to use the Azure Log Analytics Connector in my catch scope to push error info into the workspace log using a custom table.
  12. Ensure all Azure Services have instrumentation keys. Common examples are Azure Functions, Azure Service Bus, API Manager, the list goes on...
  13. Do you implement custom APIM monitoring configuration?
  14. Do you use the SDK in your code (Functions etc.)?
  15. Setup Availability tests - super useful for 3rd party API's.

Once you have the logs captured and traceable (Monitor & Alerting Checklist):

  1. Create Queries to help find data
  2. Create monitoring dashboard using the data
  3. Use OOTB monitoring for Azure and the platform
  4. Consider linking/embedding to other monitors i.e. Power Automate, DevOps, Postman Monitor
  5. Setup alerting within the Azure Log Workspace using groups, don't over email.  For information alerts, send to Slack or Teams (very simple to setup a webhook or incoming email on a channel to monitor)
  6. Power Automate has connectors for adaptive cards channel messaging, consider using directly in Flows or from alerts, push the data into a flow that will log the alert using an adaptive card right into the monitoring channel.

Sunday 19 February 2023

Setting up Azure Application Insights for Monitoring Power Platform Canvas Apps

Overview: We are building key applications in Power Apps.  It is essential that the appropriate level of monitoring, alerting, and ability to trace is setup.  The diagram below provides an overview of likely solutions.  

The top half of the diagram should call out the client components used in the application, you need to add instrumentation keys to ensure the logging is done to the correct DTAP environment instance, i.e., production components used in the solution must point to the production instance of Azure Application Insights.  The diagram only deals with Production.  I prefer to point the lower env to a non-pro instance.

The bottom half discuss decisions that are key to make the monitoring and alerting successful.  It should aim to:
  1. Ensure errors are detected, 
  2. Can be traced,
  3. System is healthy, 
  4. Are any components down,
  5. Performance is stable or not,
  6. Warn me before the system goes down,
  7. Alerting is setup (don't over alert and ensure it is focused to the right people), and
  8. Validate deployments.     
I turn on the experimental features:

A gotcha to App Insights in Canvas apps applies to Managed solutions, if you add an app insights instrumentation key, or leave it blank, there is no easy way to override the value.  You can add an unmanaged layer but the issue is when you next deploy the app only updates the the new version once the unmanaged layer is removed and you will need then then manually add the Unmanaged layer after each deployment with the appropriate app insights instrumentation key.  There are workarounds with extracting the solutions and amending the setting, then repackaging using the Power Apps CLI but it has issues.


Other thoughts:
It is a good idea to use the App Insight SDK's to trace key info within each service
Power Automate should use the try catch function pattern for logging.  I log to Azure Log Analytics using the built in Power Apps connector.

Monday 24 January 2022

CorrelationId thoughts for improved logging in SPAs

Problem:  Single Page Applications (SPA) generate a new correlationId/guid on path changes only, when logging to something like App Insights, the SPA using a framework like Angular will have a page view with multiple actions that are logged using the same guid.  

Initial Hypothesis: You can work out the users journey by using the page view guid and tracing the actions to drill down to the issue.  It is far easier to generate a new guid for each action making error tracing simpler/faster for 1st line support.  Also performance issues are far easier to replicate and automate reporting on for changes in performance.   

SPA/Angular Resolution:

  1. import{ Injectable } from'@angular/core'; 

  1. import{ ApplicationInsights } from'@microsoft/applicationinsights-web'; 

  1. import{ environment } from'src/environments/environment'; 

  1.  

  1. @Injectable({ 

  1.   providedIn:'root' 

  1. }) 

  1. exportclassAppinsightsLoggingService { 

  1.   appInsights: ApplicationInsights; 

  1.   constructor() { 

  1.     this.appInsights = newApplicationInsights({ 

  1.       config: { 

  1.         instrumentationKey:environment.appInsights.instrumentationKey, 

  1.         enableRequestHeaderTracking:true, 

  1.         enableCorsCorrelation:true, 

  1.         loggingLevelTelemetry:1, 

  1.         enableAutoRouteTracking:true// option to log route changes 

  1.       } 

  1.     }); 

  1.     this.appInsights.loadAppInsights(); 

  1.     this.appInsights.trackPageView(); 

  1.   } 

  1.  

  1.   logPageView(name?: string, url?: string) { // option to call manually 

  1.     alert(name); 

  1.     this.appInsights.trackPageView({ 

  1.       name:name, 

  1.       uri:url 

  1.     }); 

  1.   } 

  1. } 


  1. public getTraceId (){ 

  1.     returnthis.appInsights.context.telemetryTrace.traceID; 

  1.   } 

  2. // Call when needed


Note: Thanks to Pravesh Chourasia for showing me how to do this.