Showing posts with label Logging. Show all posts
Showing posts with label Logging. Show all posts

Tuesday, August 15, 2023

Azure @ Enterprise - Configuring PnP.Framework SDK logs to trace file

Context

Environment - Microsoft Azure Virtual Machines

Technology - .Net Framework 4.8, SharePoint Online

Functionality - Interacting with SharePoint Online via Graph SDK and PnP.Framework, Mainly uploading a large number of files.

Requirement - Trying to collect the logs emitted by PnP.Framework especially the HTTP calls.

Solution

The PnP.Framework emits the traces by default using the standard .Net Trace class. Note it is not the ILogger that is now the standard after .Net Framework. Refer to the source code to ensure they change in the future. There is an ILogger class involved but that is not the same .Net Core uses. 
  • .Net Core programming model - Microsoft.Extensions.Logging.ILogger & Microsoft.Extensions.Logging.ILogger<TCategoryName>
  • PnP.Framework - PnP.Framework.Diagnostics.ILogger
The default implementation of PnP.Framework is using TraceLogger class which is implemented by the same SDK. It uses the Trace class as mentioned above. So if we don't configure anything else, we can collect the logs to a file using the below configuration changes in app.config or web.config.
<system.diagnostics>
    <trace autoflush="true" indentsize="1">
      <listeners>
        <add name="Listener1" type="System.Diagnostics.TextWriterTraceListener" initializeData="path\to\file.ext" />
        <remove name="Default" />
      </listeners>
    </trace>
... 
</system.diagnostics>

Here ends the basic solution to the problem. Anytime PnP.Framework SDK logs it will be saved to the file mentioned in the <listeners> section.

Log Level

By default the PnP.Framework logs at 'debug' which is strange.
But that can be changed with some adjustments. Config changes goes below
<configSections>
    <sectionGroup name="pnp">
      <section name="tracing" type="PnP.Framework.Diagnostics.LogConfigurationTracingSection,PnP.Framework"/>
    </sectionGroup>
  </configSections>
  <pnp>
    <tracing logLevel="Debug">
    </tracing>
  </pnp>

Tuesday, March 28, 2023

Azure @ Enterprise - Writing custom functions in LogAnalytics KQL

Normally when we analyze web requests we encounter scenarios where the URLs have values such as GUID. That will cause little trouble when we want to aggregate. Without replacing those values if we aggregate, it will be showing many categories based on the cardinality of values. For example, if we are taking the max time taken by URL, it may be showing a different URL when with the GUID values and without GUID values.

In Azure world, we mainly use LogAnalytic, Application insights, etc... for storage and the Kusto Query Language (KQL hereafter) for querying data. The same problem of numbers and GUIDs in URLs will be a problem here as well.

The title of this post is not about replacing GUIDs using regular expressions. But the replacement of GUIDs is going to be demonstrated using a custom function in this post

Without GUID removal

Let us see a sample without filtering GUIDs


With GUID removal

Here goes the result of the GUID removal
In the above example we can see when we replace the GUID values, a new URL showed up. This is useful to decide what URL to optimize when we have limited time in hand.

GUID removal with function 

First, have an understanding of how to write user-defined functions in KQL and the difference between scalar and tabular functions.

Below goes the equivalent code with the function that replaces GUID values with string /GUID.

Tuesday, March 7, 2023

Azure @ Enterprise - Application Insights string split to find distinct databases from dependencies telemetry

Problem

We have access to the application insights of a distributed application. We don't have access to the server's inventory. But we need to get the database count and names.

This looks like a fresher interview question but this kind of scenario can happen in a real work environment. There is always a reason for asking these questions in fresher interviews.

Solution

It may feel easy as below Kusto query. The database names are in the 'dependencies" telemetry table.

Tuesday, July 26, 2022

Modernize legacy .Net Framework WebApi apps with .Net Core ILogger & DI

This post is advised to read after the previous post about modernizing the .Net Framework console app to use .Net Core Programming model without changing the runtime. It helps to slowly migrate large monolith .Net Framework apps into .Net.

This post is about slowly migrating legacy WebAPI applications in the same way. ie adding DI using ServiceCollection and ILogger without changing the .Net Framework runtime.

Sample source code

This time there is no video tutorial. Let us look at the actual code itself.

Below goes the areas that need to be changed to get dependency injection from the Controller classes themselves.

Creating the ServiceCollection

This is obviously the first step in doing the DI.

Hope the code is explanatory if we have some basic idea about the .Net Core programming model. The Get() returns the ServiceProvider after configuring ServiceCollection.

Overriding DependencyResolver

It's easy to see the code first.

We just added our own DependencyResolver. Next, let us see what is in that new resolver class.

This facilitates the creation of objects as and when asked by the ASP.Net WebAPI framework.

ILogger Support

Nothing special to be done. The ConfigureServices() in ServiceProviderFactory class does it.

References


Tuesday, July 19, 2022

Modernize legacy .Net Framework Console apps with .Net Core ILogger & DI

There are already lot of  tools and techniques to modernize .Net Framework applications by migrating to .Net. There is a question what modernization we are getting by changing the runtime without changing the architecture or at the minimum UI? That question we are keeping aside and taking the requirement of modernizing a decade old legacy monolith .Net Framework app having a million lines of code. 

Here the tools can do limited things. That app may be not at all having the concept of Dependency Injection, lot of COM components used and built on top of WCF and old remoting. On top of that if there is no budget to reserve a release just to modernize.

None of the quick techniques works there. One strategy could be to modernize it part by part. At least to start with we can start refactoring to the Dependency Injection using ServiceCollection and ILogger usage similar to .Net Core and .Net Application. 

The question may come can we use these .Net Core programming model in .Net Framework apps. The answer is yes if we are in .Net 4.8 or a version that supports the nugets. We should really thanks to the concept of .Net Standard and design of modern .Net as modular using nuget packages.

One such mechanism is explained in the below video. 

We can still stay in .Net Framework and we can use .Net Core Programming model such as Dependency Injection and ILogger usage.


  

Source code is available in GitHub.

Tuesday, January 4, 2022

Using ILogger in minimal .Net ASP.Net Core API Application

.Net 6.0 introduced the minimal API model for WebAPIs. That is highly reducing the amount of boilerplate code to be used to run WebAPIs. All actions can be included in a single file. This post is not to explain the wow factor of the Minimal API model but to give some tips to use ILogger in minimal APIs.

Using ILogger outside of action method

This is about using the ILogger in the Program.cs

Tuesday, April 20, 2021

Azure @ Enterprise - Tracing to Console in different Azure SDKs for .Net

Introduction

Microsoft constantly improves the SDKs. As a side effect, we have to work with new SDKs. Earlier SDK names start with MicsoftAzure or WindowsAzure, next it was Microsoft.Azure. The recent one starts with Azure. Sometimes it's easy to migrate to the latest SDK, but sometimes it's difficult. There is one full post about the dilemma of choosing the Azure SDKs.

The best practice is to be with the latest and greatest version of SDKs

Every time the SDK changes, the logging mechanism also may change. This post is to discuss differences in SDK logging. For simplicity, we are going to look at the logging mechanism that outputs into the console. The same mechanism can be leveraged to write into any other persistent storage.

Why logging is important?

It really depends on the time developers are getting to release products in quality. But whatever the case today or tomorrow we as developers will end up debugging why our code failed in certain situations. The Azure works by HTTP WebAPIs and these SDKs are mainly wrapping that HTTP requests. If we are running in an unrestricted environment, we may not encounter any issues. But if it is from an enterprise environment that has its own hardening policies and restrictions, we will definitely encounter issues and end up debugging. If we are able to see the requests payloads in the console, it would be easy to debug at least in development time. Or just be use our friend Fiddler.

Azure.*

Let us start with the latest SDK as of today. Not sure if it's V12(Storage Blobs) or V4(KeyVault Secrets) or V7 (ServiceBus). The nuget packages are all starting with Azure. are the latest. It all starts from this GitHub repo where the source code lives. There is a documentation page that explains how the logging can be achieved using these SDKs. The essence of the approach is as follows.

Tuesday, October 15, 2019

[Video] - Power BI Desktop Dashboard for IIS Log Analysis - Step by step instructions to prepare IIS Logs files and loading into PBI

Today lets see how to prepare IIS Log files to load into Power BI Dashboard. The 'software-performance' GitHub repo contains sample IIS Log files along with the tools. We can use the same for the demo.

Prerequisites

Below are the prerequisites to complete the steps which help us to analyze IIS Logs via Power BI.

  1. A machine with Windows OS as all the tools used are compatible with Windows only.
  2. Basic understanding of Windows PowerShell
  3. LogParser utility
  4. Of course the Power BI Desktop application.

Steps

Let's see the steps

  1. The first, step is to clone the 'software-performance' GitHub repo into a local directory. How to clone a repo is not in the scope of this tutorial. Please refer to the link provided. Let's consider is it cloned into c:\source\repos folder
  2. Second step is to convert .log files into .csv. Open Windows PowerShell ISE better "run as administrator". Then navigate to the cloned folder where the IIS to CSV.ps1 file is available.
  3. Once we open the IIS to CSV.ps1 file, make sure the variable $pathToLogParserExe has the correct path to the installed logparser.exe file
  4. Change the value of $inputPath to the folder where IIS Log files are located. Let's use the sample logs provided in the software-performance repository.
  5. Run the script by clicking the button of press F5
  6. It will convert the .log files to .csv files. We can see the CSV files created in the same folder of input log files.
  7. Now open the Power BI sample file present in the repo
  8. Click on the Edit Queries drop-down then- > Data source settings
  9. We can see the current folder used. Click on the 'Change Source' button in the bottom left. Enter the path to the folder where CSV files created
  10. Press Ok then Close buttons.
  11. Finally, click on the 'Refresh' button. It will load the data from files into Power BI and render reports.
It may take more time depending on the size of CSV files. Normally the speed is observed as 1MB/second.

The same steps along with a short description of dashboards available in the below video

Tuesday, October 8, 2019

Azure @ Enterprise - Where is Diagnostics logs settings blade of App Service Web App

This would be the simplest post in this blog. It is nothing but a renaming happened in Azure App Service.

Background

Enabling diagnostics is essential for most of the Azure resources especially if we are moving to Azure with teams that are not ready to use Azure. The teams refer to the different functional teams in the application life cycle such as developers, testers, installation team and finally the support.

Problem

Earlier we used to see the diagnostics logs as its proper name under the 'MONITORING' section. Our installation documentation will have this name refers to the installation team. See the below.

But later this was simply changed. People are confused about where it is relocated especially who those are not working every day with Azure but occasionally going there to install or configure applications. They are doing it because they only have access to the Azure portal. The application installation documentation might not be caught with this name change. 

How Microsoft handles renames

Forget about us as application developers not changing the documentation to include the new name, Microsoft itself took some time to update their documentation. As part of embracing open source and as part of feedbacks, Microsoft changed to an open documentation model. After that, the responsibility of making sure the documentation is up to date seems shifted to the community than Microsoft as a vendor. The good part of that open documentation repo is in GitHub and we can easily trace the change.

Below is the trace of communication in the form of GitHub issue regarding the name change from "Diagnostics logs" to "App Service logs".

https://github.com/MicrosoftDocs/azure-docs/issues/33044

The issue logged 10Jun2019 and completed just 20 days ago as per the issue history. Really interesting to read.

So where is Diagnostics logs settings blade of Azure App Service?

It got renamed to App Service logs. The new screenshot goes as below.

Tuesday, September 24, 2019

Power BI Desktop Dashboard for IIS Log Analysis - C# for IIS log parsing instead of PowerShell

Introduction

The last post in this blog was about Power BI to analyze IIS logs. It used Log Parser and PowerShell to prepare the W3C IIS .log files into CSV. That conversion is needed as Power BI don't understand the W3C log file format produced by IIS. Though it works for small to medium load, it takes more time to prepare larger files. Let see another way to prepare IIS logs to CSV for log analysis.

Limits of log parser

One of the limit is it cannot output a default value if the columns are not available in the source log file. At the other side Power BI needs all the columns in CSV to load data. This mismatch happens frequently as the default setting of IIS web server doesn't include the cs-bytes and sc-bytes columns and the PowerBI needs that to analyze the payload.

The solution was to load the CSV produced by Log Parser into PowerShell and add missing columns and output the same into CSV file. PowerShell loading the CSV and adding columns is time consuming out of the box. We can tune the PowerShell script to optimize CSV handling. But still, there will be 2 tools IISLogParser and PowerShell.

Enter C#

What if we use C# to convert the IIS Logs to the desired CSV with default values? It is not advisable to rewrite the IIS log parsing logic in C# and maintain the same. It is better to use a library from nuget. Fortunately, there is one library called IISLogParser. We can use the same to parse the logs and use CSV libraries such as ServiceStack to output into CSV.

It is easy to set up such utility in C#. Source code can be found at below GitHub location.


Please note that this uses .Net Core 2.1 target. Ideally, there should be no issues in adding full .Net framework version as target as those libraries support multi-targeting. Add an issue in GitHub repo in case of issue better with PR. Comments in this post also welcome. 

References

https://stackoverflow.com/questions/32120528/parse-iis-log-file-is-there-an-alternative-to-logparser

Tuesday, September 17, 2019

Power BI Desktop Dashboard for IIS Log Analysis

Introduction

As developers, we all might have encountered situations of analyzing IIS web server logs. During the development time, the file is small and easy to analyze in Notepad or Excel. But when it grows to GBs in production servers we use other tools. One such popular tool to query IIS logs is LogParser. It is a free command-line tool from Microsoft. There are graphical applications around it to generate even charts. One such free tool is the Log Parser Studio. It is also from Microsoft.

Once we move up in career and had to deal with managers, product stakeholders or even to CXO to show what the IIS logs say, we need more visuals or a dashboard reflecting the IIS logs. Though we can create visual using Log Parser Studio, it is tedious creating reports and charts one by one. 

One easier solution is to get in Azure and use Azure AppInsights which has built-in dashboards. We can do customizations easily. There are other services like Application Insight also such as Dynatrace, Retrace, etc...But the problem is that not all of us gets the luxury to buy the software and services we want. Sometimes our organization or clients may not be willing to buy. So let's look for other free solutions.

Enter Power BI

Power BI Desktop is a free visualization tool from Microsoft. It can easily produce great-looking visuals with data insights.
Fortunately, this is not the first post on PowerBI for IIS W3C log analysis. There is already one out. We are using it as a base and adding some more features.

https://blogs.msdn.microsoft.com/kennethteo/2018/04/27/analyzing-w3ciis-log-with-powerbi/

Prerequisites

Tools 

  • LogParser
  • Power BI Desktop - Free version is enough
Experience
  • Basics of PowerShell
  • LogParser queries.

Data preparation

The post by Kenneth uses .bat commands to trigger LogParser to convert .log files from IIS to csv. Those queries have hardcoded column names. The problem with that is we cannot just add more columns from IIS logs. Example cs-bytes and sc-bytes are the columns which are not enabled in IIS by default. Ideally, the solution is to use 'select * ' in the LogParser query. But the problem is that Power BI doesn't support (or more research needed) a flexible number of columns in CSV mapped properly to fixed columns. 
Hence using PowerShell to invoke LogParser which first try to convert .log to .csv including cs-bytes and sc-bytes. If those columns are not available, it tries without those columns which are the default setting in IIS. If those columns are not available, 0 / default value will be used.

PowerShell can be downloaded from the below location.

How to run PowerShell

  • Use the IIS to CSV.ps1 
  • Change the $inputPath to the folder where .log files are located
  • Run the ps1 file
  • The output .csv files will be generated in the same folder location.
Power BI template provided by Kenneth in his post has to be updated to reflect this change. Let's see those changes

Separation of concerns in Power BI dashboards

The Power BI template used by Kenneth has fewer reports and visuals. Obviously, that seems towards proving a concept. Let's add more visuals such as a dedicated page for errors, errors by server-ip to identify faulty servers.

Sample

Step by step instructions to add more visuals is not necessary as the PBI template itself can be shared and anyone can load their own data to it. Sample Power BI having more visuals has been uploaded to below location.

https://github.com/joymon/software-performance/tree/master/web/iis/log-analysis/Power%20BI/PBI-Template

Just prepare the CSV from .log files and update data source in PBI to reflect the changes in visuals.

Feel free to download and try it out. Any suggestions are welcome in Github as enhancements.

References

https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/6752494-web-servers-on-premise-for-iis-log-data
https://community.powerbi.com/t5/Desktop/IIS-log-files-convert-queries-to-PowerBI/td-p/166160
https://ittechnews.net/microsoft/official-microsoft-news/analyzing-w3c-iis-log-with-powerbi/

Tuesday, August 13, 2019

System.Diagnostics logging in .Net - Trace sources

As developers, we often need to work with network issues. The first step is to finding out there is a network issue such as delay or package loss. This can be found by looking at Wireshark. But Wireshark needs some expertise. Also, it needs installation and mostly a restart after installation. When working in production environments it would be difficult to restart. But the other side is we can analyze without any changes to the application as setting diagnostics source needs application config changes.
But if we just consider the expertise needed for Wireshark, a better way is to collect some svc logs using Diagnostics. If required go for Wireshark as the second step of the analysis.

Diagnostics sources related to Network

We are not going to create another list. Below are the links to already existing tutorials

General networking

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-configure-network-tracing
https://blogs.msdn.microsoft.com/waws/2017/03/14/how-to-get-a-system-net-trace-of-your-c-web-job/

WCF

Legacy ASMX

Other diagnostic sources

Since diagnostics source tracing is .Net feature, there are other diagnostics sources as well useful in different scenarios. Below are some collections.

https://stackoverflow.com/questions/2464071/what-is-the-list-of-trace-sources-supplied-by-the-net-framework

Unfortunately, it seems there is no official link of the full list of trace sources.

Tuesday, July 9, 2019

IIS Web server log parsing - URLs which takes highest percentage of time and payload

Identifying where to start fixing performance issues to increase throughput is a tricky question, if we are new to the web application. One way to find out what to fix is to find the costly URL operations in the application. If the IIS logs are available we can check what are the URLs taking highest % time in a given duration they are costly in the system 

Sometimes each URL may be taking 1 second but there are millions of instances and some other times there are less instances but each instance might be taking 10s of seconds. So finding the % of time a particular URL or pattern taking from the total request time if a good start than taking a long running but less in number URL request.

This helps if we need to increase the throughput of existing system or want to reduce the hardware maintaining the same throughput.

Below are the queries to find out the candidate URL. The fix has to be done by analyzing the URL and what and how it does internally.

Percentage of time spent time-taken

/*This script finds out what are the requests taking highest % of time in the entire duration of IIS logs
Better place the URLs to remove ids, GUIDs to find unique URLs*/

SELECT TOP 500  cs-uri-stem,
  COUNT(cs-uri-stem) AS TotalRequests,
  SUM(time-taken) AS SumTime,
  MUL(PROPSUM(time-taken), 100.0) AS PercentTime,
  MAX(time-taken) AS MaxTime,
  MIN(time-taken) AS MinTime,
  AVG(time-taken) AS AvgTime
FROM '[LOGFILEPATH]'
// WHERE condition for proper filtering
GROUP BY cs-uri-stem
ORDER BY PercentTime DESC

Percentage of % payload size 

SELECT TOP 500  cs-uri-stem,

  COUNT(cs-uri-stem) AS TotalRequests,
  SUM(sc-bytes) AS SumSCBytes,
  MUL(PROPSUM(sc-bytes), 100.0) AS PercentSize,
  MAX(sc-bytes) AS MaxSCBytes,
  MIN(sc-bytes) AS MinSCBytes,
  AVG(sc-bytes) AS AvgSCBytes

FROM '[LOGFILEPATH]'
// WHERE condition for proper filtering
GROUP BY cs-uri-stem

ORDER BY PercentSize DESC

Tuesday, May 28, 2019

IIS Logging time-taken = server request processing time + NETWORK TIME

When we do application development and hosting ourselves its an easy life. If something we miss, our nights and weekends are simply gone. A different kind of easy life. But what if we develop and someone else host and maintain? It adds additional efforts to bring both the parties into same page regarding root cause of errors, performance etc...

Most of the enterprise world works as 2 separate teams for development and hosting. One of the issue  in syncing both operations and development regarding performance often arise is around the IIS logs. IIS logs shows 5 digits or 6 digits values in time-taken field. It may simply reach to development as application issue. Most of the administrators know time-taken field includes the network time to move the payloads along with execution time. But still there are admins who just pass over those issues to development without thinking what is going on the network devices, ActiveDirectory, security gateways and what not in the route.

If its clear and not expecting any of these type of issues from operation admins, please feel free to stop reading further on this post. This post is mainly intended to developers and admins who needs to know little in depth about the time-taken field and how to find the application processing time from the time-taken field.

Oh yes its simply to look at the IIS Failed Request tracing(FREB here onwards). Again feel free to stop reading as its simple as looking at FREB logs to find the network time separated from application execution time.

The below is for people who wants to reproduce a network delay and see what FREB shows. Truly for hands on enthusiasts.

Sample server application

The network delay mainly happens in below situations
  • If the payload is really large
  • Security gateways placed between the user and servers to prevent attack takes extra time in inspecting packets or if the bandwidth is really slow. 
  • If the Active Directory or other identity providers which are placed before the application is taking time.
Most of the small responses would be cached so IIS shows proper time in the time-taken field.

The test application which we are going to use has a simple web api as below.
http://localhost/TimeTakenTestServer/api/files/2

It gives random 2 MB text data back. The last number in the URL shows how many MBs of text to be returned. The WebAPI caches the random string so that subsequent requests don't need the time to generate the data. Its just reading from cache.

How to create such a request is out of this post. But for those who are interested can check out a sample in below repo location.

<Code location>

Simulate delay

Delay can be simulated in different ways.

Chrome F12 network profile

Chrome dev tools has option to introduce artificial delays. It can be used to create delays. But please note that this will not work for smaller payloads as it gets buffered in HTTP driver or IIS levels.

.Net app to slow reads using TCP API

If we use TCP classes in .Net, we can simulate delays. If we use higher level APIs, either they may not have the option to put delays or they might be reading from network level buffers.

Chrome F12 tools to demo the problem

Lets use Chrome to simulate delay. Below is the screenshot.

Chrome view



The first request is made after an IIS reset. It took around ~2 seconds. IIS needs some extra time to warm up the worker process after its reset. Note that the Fast 3G network throttle profile at the top left was no turned on at this time. 

Then tried 2 Ctrl+F5 which clear browser cache and loaded again. But this time we can see that it completed in milliseconds. This is because the server is already up and running also it has the string in memory cache (in this case a static variable)

Then the Fast 3G network throttle profile is turned on. The subsequent requests took more time.

IIS log

Let us see what IIS says about this test.

#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(Referer) sc-status sc-substatus sc-win32-status time-taken 
2019-05-21 23:23:14 ::1 GET /TimeTakenTestServer/api/files/2 - 80 - ::1 - 200 0 0 929 
2019-05-21 23:23:17 ::1 GET /favicon.ico - 80 - ::1 http://localhost/TimeTakenTestServer/api/files/2 404 0 2 17 
2019-05-21 23:23:21 ::1 GET /TimeTakenTestServer/api/files/2 - 80 - ::1 - 200 0 0 715 
2019-05-21 23:23:22 ::1 GET /favicon.ico - 80 - ::1 http://localhost/TimeTakenTestServer/api/files/2 404 0 2 6 
2019-05-21 23:23:24 ::1 GET /TimeTakenTestServer/api/files/2 - 80 - ::1 - 200 0 0 641 
2019-05-21 23:23:27 ::1 GET /favicon.ico - 80 - ::1 http://localhost/TimeTakenTestServer/api/files/2 404 0 2 4 
2019-05-21 23:23:39 ::1 GET /TimeTakenTestServer/api/files/2 - 80 - ::1 - 200 0 0 6389 
2019-05-21 23:23:47 ::1 GET /favicon.ico - 80 - ::1 http://localhost/TimeTakenTestServer/api/files/2 404 0 2 3 
2019-05-21 23:23:57 ::1 GET /TimeTakenTestServer/api/files/2 - 80 - ::1 - 200 0 0 6505

Note that the Chrome and IIS traces are not taken from exact same trial. But they are done without any changes.

FREB to rescue

Now lets see how can we understand that the transfer really took time or something wrong with application. FREB can be enabled for http 200 responses though it says failed request tracing. The FREB logs can clearly tell how much time it took for data transfer and it is displayed in the below image.


The above image shows the comparison of second request and the last request. The second one don't have any F12 Networking throttling but the last one has hence the transfer time is high.

More reading

HTTP.sys buffering at TCP layer

https://support.microsoft.com/en-us/help/820129/http-sys-registry-settings-for-windows
https://blogs.msdn.microsoft.com/wndp/2006/08/15/buffering-in-http-sys/

Tool to simulate network delay

http://jagt.github.io/clumsy/index.html

References

https://blogs.msdn.microsoft.com/tess/2008/08/19/troubleshooting-a-performance-issue-with-failed-request-tracing-and-appcmd-in-iis7/
https://blogs.msdn.microsoft.com/docast/2016/04/28/troubleshooting-iis-request-performance-slowness-issues-using-freb-tracing/

Tuesday, June 12, 2018

Azure @ Enterprise - AppInsight -> Server -> Exception rate is not correlating with exceptions telemetry

There could be surprising situations where the AppInsight->Servers page show high rate of Exceptions but when we query exceptions it will not match with the exception rate. Its is tough situation for supporting application especially when stakeholders are interested in AppInsight reports.

If the production support teams are not capable of finding out why the different occurs, it will come to development. So what is going on here?

Why EXCEPTION RATE is not the rate of exceptions telemetry?

The AppInsight->Servers page displays the "EXCEPTION RATE" graph from performance counter where the 'exceptions' telemetry is having only the exceptions which are reported to AppInsight from applications such as using TrackException() of SDK. If application or framework is eating exceptions those exceptions will be affecting the performance counter and the graph but never comes into the exceptions telemetry. We can verify by clicking edit button of "EXCEPTION RATE" to view the data element. It will be performance counter. See the image below.
We can cross check by remote login into the server and watch the counter in perfmon.exe utility. This behavior is documented by Microsoft here and here.

What are the sources of eaten exceptions?

The million dollar question is whether I should worry about this high exception rate? The answer is yes if we care about our software what we made. If the app is just working and its not mission critical and have enough budget to run the app, we may leave. But that is not the case with most of the applications especially if it is hosted in Azure. Every fault translate to money. If those exceptions are slowing down requests the entire throughput will get reduced which leads to more machines to serve less users.

OK, we are going to fix it. How to find out the sources of exceptions. As we seen in above section, perfmon.exe is a good start to find what processes are throwing exceptions. Once we know the source the fix depend on individual finding. Below are some examples
  • If we are using netNamedPipe binding to communicate between internal services, there are high chance that so many exceptions got eaten by that binding but functionality would be working.
  • If the system is consuming other Azure services and retry is implemented, there could be exceptions but retry might have solved the business scenario but the performance counter get affected by the exception. 
  • If there are any background workers running using 'On Error Resume Next' style, the exceptions encountered inside those may be eaten and affecting exceptions performance counter.
It is better to report the exception using TrackException even though we are handling it. Overall it is a tedious process but there are chances to get treasures which help us to remove one server to support same number of users.

Happy debugging.

Tuesday, August 29, 2017

Azure Application Insights - End to end correlation from Angular to internal WCF services

Azure AppInsights is one of the PaaS offering which can be easily configured to our application and leverage capabilities. And it really works without any changes in our application. But does it helps us more than any other tools? May be yes with default setup. We will really love it if we can get end to end correlation to understand what is happening in our system. Production debugging will be a breeze with correlation. 

This post is talking about how can we correlate activities happening in different tiers of our system and see it in one place. Lets take a scenario where an Angular application is interfacing with users, it calls ReST endpoints to talk to front end services and front end services communicate with other internal services. We can correlate operations originating from client side to related operations happening in the internal services.

Prerequisite

  • Basic knowledge about AngularJS 1.x
  • Knowledge about WCF services.
  • Knowledge about setting up AppInsights service

Sample setup

It is advised to download the sample from below location before reading further. Below goes the structure of sample.

AngularJS application just does one thing. Finding the area of circle if we give radius. For finding area, it calls a ReST web service.
It sends one event during startup. Another one during calculating the area ie when calling the FronEndWCFService. These are custom AppInsights events

FronEndWCFService is a simple WCF service hosted using webHttpBinding to get ReST end points. It calculates the area using the parameter radius. It don't know the value of pi. It dependent on InternalService to get the value of pi. During the calculation it sends some custom events/operations to AppInsights.

InternalService is hosted using net.pipe binding. It has one method which returns the value of Pi. It also sends some custom events to AppInsights.

The above 3 components are hosted inside IIS and enabled with AppInsights for default system events.

Running the sample

  • Make sure the 3 web applications are hosted in IIS.
    • The web application has to net.pipe binding to host InternalService.
    • Try to browse the service Urls.
  • Give the Url of InternalService in the web config of FrontEndWCFService so that it can call.
  • Obtain AppInsights instrumentation key by either creating a new instance in Azure or copy from existing AppInsights instance. Replace this key into web applications. Better use visual studio search and replace and the word to replace with key is {Your Key} .There are 3 files to get the instrumentation key. 
    • /AngularClient/Views/Shared/_Layout.cshtml
    • /FrontEndWCFService/ApplicationInsights.config
    • /InternalService/ApplicationInsights.config
  • Run the AngularClient application in browser.
    • During the application load, it will log "Custom init event from JS"
    • When we give the radius in the text box and click on button it will log "Custom event from JS before service call"

Viewing the AppInsights

It may take some time to get the entries reflected in the AppInsight in the Azure portal. It is better to go to the analytics portal of ApplicationInsight instance and view the results. In the analytics portal, the details can be seen as follows.

The entries highlighted in the name column are the custom events generated by different tiers in the system. Along with custom events the system will generate event if AppInsights collectors are attached to the processes. That can be done by connecting interceptors in the WCF or HttpModules in Web request pipelines.

Understanding correlation results

The operation_id column is the id which really correlate the operations. The id has to be unique and the parent_id can be any id used previously. It can be a tree of related events.

Don't get confused on the term 'events' used here. AppInsight can accept events, operations, traces etc...For easy reference term event is used.

Q&A

How does a web request from Angular gets correlated with servers

When we send web request from Angular or any client if we send http header "Request-Id" it will be treated as operation_id by server side, if we have the AppInsight request interceptors

Why the sample has 2 methods in Angular to write custom AppInsights

When the application is getting initialized, the appInsights object may not have the context ready.If so we have to put into queue. Once the context is initialized, we can use it to set operation_id. At that point the queue will be null.

Should I write any code for intercepting incoming web/WCF requests to read correlation data?

No we just need to use already available nuget packages and setup our web.config appropriately.

Should I write any code for intercepting the out going web/WCF requests to write correlation data?

No we just need to use already available nuget packages and setup our web.config appropriately.

References

https://docs.microsoft.com/en-us/azure/application-insights/application-insights-correlation
https://github.com/Azure/diagnostics-correlation
https://github.com/Microsoft/ApplicationInsights-JS
https://github.com/aspnet/Microsoft.AspNet.TelemetryCorrelation
https://mitra.computa.asia/article/msdn-modifying-and-filtering-telemetry-appinsights-javascript-sdk-telemetry-initializer

Tuesday, June 13, 2017

Interception in Microsoft Unity framework for .Net

Introduction

This article is to demonstrate how we can combine dependency injection framework with logging og low level execution flow of application.

Prerequisites


  • Knowledge about dependency injection.
  • Knowledge about unity from Microsoft for dependency injection

Background

If we develop any application, logging is an essential thing to troubleshoot issues which comes in  later stages. Ideally there should be no bugs in production, if we test well. But it is not practical 99.99% of times. Sometimes even if there are no defects we may need to understand how the system is getting used. We call it as instrumentation, telemetry etc...Whatever we call, we have to make sure our application is capable of telling us what it did. Writing log lines inside our business logic has more efforts/costly, makes it longer and very difficult to read. 

Instrumentation technology considerations

Below are the factors to be considered when we select any logging and instrumentation technology for software.
  • Performance - Due to the logging operations our application should not be performing slow. Logging is for application not the other way.
  • Controlling behavior - We should be able to turn the logging on and off without restarting the application. Also change the level of logging without restarting.
  • Compatibility - If our system spans across different technologies better choose one which works everywhere.

Options

Traditional options include inserting log lines at the beginning and end of every methods and additional lines if the logic inside complicated. Another option is to inject the logging code at runtime. Both has their own pros and cons.

Few words on ideal composed application

If we look at SOLID principles we could see that all it tells us is to develop apps in a modular way where modules can be composed easily. In other words single responsible, closed components connected together to become an application. When we say modules, components in general they all translate to classes or functions in code.

How we compose the application by connecting the components is via dependency injection framework.

Combining DI framework and logging

Now most of the people might have got the click of idea. If the application follows SOLID principles religiously, why can't our DI framework log the method calls as it knows how application is composed. When we say how the application is composed it is same as the application flow which we need to log.

This is supported in Microsoft unity framework which provides DI capabilities for .Net. There are other DI frameworks available, one other called MEF which is native to .Net itself. This post is not to discuss what is the best DI framework but on the possibilities of combining DI with function level logging.

Steps in general

  • Have a interceptor mechanism which can tell us what is happening in the DI framework
  • Let the interceptor log the details into appropriate medium using best technology.
  • Register the interceptor into the DI framework.

Understanding sample

Coming directly to the sample which is available in the below location.
https://github.com/joymon/dotnet-demos/tree/master/patterns-practices/DI/unity/Interception

class LogCallHandler : ICallHandler

This is the interceptor we have written. It has Invoke() implemented which came via ICallHandler. Invoke() will be called by the unity DI framework when things happen there.

This is one mechanism unity supports. There are other ways to hook interceptors.

UnityConfiguration.xml

This is the configuration file which tells the unity framework about the components and how they composed. In simple words when someone request object of x interface give object of y class which implemented x. This file also has options to register interceptor.

This configuration can be specified via code too.

class Logger

This is a simple logger class which logs via .Net trace. .Net tracing is configured in the sample to write to file.Refer app.config file. We have to consider intercepting the method calls and writing the logs separate. If our log writing takes more time the performance of application may get affected. Choosing log writing mechanism is not in the scope of this article. In short, recommended mechanisms are ETW for on premise and Application insights for Azure environments.

References

https://msdn.microsoft.com/en-us/library/dn178466(v=pandp.30).aspx
http://mohtasebi.com/patterns/2013/10/24/using-unity-for-aspect-oriented-programming-and-interception-part-1.html

Tuesday, July 28, 2015

Best practices in SSIS Logging


  • Log always using SSIS logging mechanism
  • Do not reinvent logging mechanism using any manual methods even in C# script tasks
    • Script task to log into SSIS logging stream
      • http://dataqueen.unlimitedviz.com/2013/09/how-to-enable-custom-logging-for-an-ssis-script-task/
      • https://msdn.microsoft.com/en-us/library/ms136131%28v=sql.120%29.aspx?f=255&MSPPError=-2147217396
  • Inject the log destination from invoking platform. This will help to correlate the SSIS logs with other application logs.
    • eg: If the SSIS is invoked from C# application let the C# provide the logging connection string.
  • Better log all the events and point to database as logging store.
  • Have periodic routine to cleanup the logs.

Above are the best practices as of my understanding and experience with SSIS. Sorry to say that, I cannot guarantee that it will work for all.

Tuesday, August 9, 2011

IIS log analysis

Recently I got a golden opportunity to go Microsoft campus located in Charlotte ,NC and work with Microsoft guys .It was related to capacity planning of our project.The project uses Silverlight technology and obviously there are WCF services to supply data to the Silverlight application.Our main aim was to do capacity planning for the WCF service side and also the database. There I got chance to work with some tools which are available for years but never used by me.One of the tool was IIS log parser.
As name implies it is the tool to parse iis logs using sql kind of queries.You can easily find out what are the top 10 file types your iis is serving or what are the top 10 urls which are requested more etc…If you are a web site production support person, this will be childish.But for a developer who just code web sites and haven’t seen how his code is performing in the production this will be a key for him to the production world.

What are IIS logs and where can I find?
These are the log entries which IIS maintain for the requests it receive and serve.by default the logs will be in the %SystemDrive%\inetpub\logs\LogFiles folder in your machine.The log file writing is normally separated by number of factors.They are generated per web site , per day etc…Also we have option to specify which all fields should be included in the log files. For example we can avoid client IP address and referrer from the logging and add number of bytes sent and received.Ok now developers who doesn’t seen this might be excited to see the logs and how to configure it. Just open your IIS and select the Logging option at the right side and double click. Rest is very simple as some clicks.A screen shot below.

For more details about how to configure and analyze the logs see the below links.

http://technet.microsoft.com/en-us/library/cc732079%28WS.10%29.aspx
http://blogs.iis.net/carlosag/archive/2010/03/25/analyze-your-iis-log-files-favorite-log-parser-queries.aspx

Wednesday, January 20, 2010

My First Look at EnterpriseLibrary.Logging

Last week I got opportunity to work with the logging module of our application.It was done by one of my colleague and he told that it is done using Logging module of .Net EnterpriseLibrary.
After looking around the code, I was surprised on the lines of code below which does the logging.Rest is all taken care by configuration entries in web.config.

using (new Tracer("My Tracer"))
{
LogEntry le = new LogEntry() { Message = message };
Logger.Write(le);
}



When I looked into the web.config I was able to see some entries in a section named loggingConfiguration




<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />



The above code should be inside configSectionsTag.The rest is a new section as follows added after the config sections.




<loggingConfiguration name="Logging Application Block" tracingEnabled="false"
defaultCategory="" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="log.log"
header="-------------Log Message---------------------"
rollFileExistsBehavior="Increment"
rollInterval="None"
rollSizeKB="1024"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None"
filter="All"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="FlatFileListener" />
</listeners>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors &amp; Warnings">
<listeners>
<add name="FlatFileListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>



I hope the config is self explanatory.It uses a flat file writer which writes into the file log.log present in the root directory.

I usually afraid of these config entries which cannot be memorized by a developer.If you are also afraid of the config entries use the Enterprise Library Configuration Tool.


This is just a sample.There lot more things which we can do with the logging application block such as format the text which is writing into the file.More properties such as priority,category etc…,Variety of logging  locations such as database,email etc…If I get some more extra time I will surely blog about the same.More details can be found in the below links.



http://bloggingabout.net/blogs/dennis/archive/2009/07/21/quickstart-tutorial-into-enterprise-library-logging.aspx


http://www.codeguru.com/csharp/.net/net_framework/systemnamespace/article.php/c11281/


http://www.codeproject.com/KB/architecture/GetLoggingWithEntLib.aspx



NB : Don’t forget to download the CAB and add reference to the following dlls when  you start a new project.




  • Microsoft.Practices.EnterpriseLibrary.Common.dll


  • Microsoft.Practices.EnterpriseLibrary.Logging.dll


  • Microsoft.Practices.ObjectBuilder2.dll



I have uploaded a sample here.