Here is the link to the "home page" for this blog serie.

The next point of interest is logging. The logging is very important for application life cycle. Take time and be careful when you pick up which logging tools/software you are going to use. If you can use Azure just use Application Insights and you done. It's just unbelievable good microsoft product and you can log there from everywhere. Take a look at docs. It's very easy to configure and use. Another option is of cause  log to database, but you have to find out how you are going to visualize your data.

Don't use Event Viewer. Event Viewer is good just when you are developing and debugging your service.  And I can give you some explanation why I think so

  • It's impossible or very difficult to visualize your logs
  • you have to login to the server to see the logs and often it's only two persons who can login to the server at the same time
  • it's not shortcut friendly. Just to take a look whether your service started or not you have to click approximately 100 times. And when you are responsible for like 10 or more windows services it is quickly became a nightmare.

I am going to walk you through how to log to Application Insights. Log in to your Azure portal, if you don't have one read my blog how to create it.

First we are going to create a new Resource Group.

Click on Create a resource

Create a resource

Start to write resour and

Create new resource

And choose Resource group

Resource group create

Click on Create.

Create a resource group

Choose Subscription, resource group name and region then click on Review + Create.

Click on newly created resource group and click on Add

Add resource

Start to write appl

Find Application Insights and click on it.

Application Insights

Choose the Name, Type, Subscription and Location. I choose to use existing resource group and for Application Type - just General. Click on Create.

Now click on Application Insight resource and find Instrumentation Key.

WindowsServiceAI

Copy and paste it somewhere. We are going to use it in our application.

Now back to Visual Studio.

Add Microsoft.ApplicationInsights NuGet package to the application by right clicking on the solution and choosing Manage NuGet Packages for Solution...

Manage NuGet Packages for Solution

Choose Browse and paste in Microsoft.ApplicationInsights

Choose the project and Latest stable version and click on Install.

And install also following  latest nuget packages

  • Microsoft.ApplicationInsights.DependencyCollector
  • Microsoft.ApplicationInsights.WindowsServer

Open the program.cs class and add

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

and add following code to the main method

var key = "541b2793-939c-47c3-b62f-717d1b1420a9";
TelemetryConfiguration.Active.InstrumentationKey = key;
TelemetryClient aiClient = new TelemetryClient();
TelemetryConfiguration config = TelemetryConfiguration.Active;

Now we can log data to the Aplication Insights by f.ex. using TrackTrace method

Our main method looks like this now

static void Main(string[] args)
{
    var key = "541b2793-939c-47c3-b62f-717d1b1420a9";
    TelemetryConfiguration.Active.InstrumentationKey = key;
    TelemetryClient aiClient = new TelemetryClient();
    TelemetryConfiguration config = TelemetryConfiguration.Active;
    try
    {
        aiClient.TrackTrace("Our service running just fine and some more info");
        StartProgram();
    }
    catch (Exception exception)
    {
        throw;
    }
}

Open ApplicationInsights.config file and paste your instrumentation key to the top of this file

ApplicationInsights.config

Now run your application and observe that you log some data to the application insights. You can do it inside Visual Studio or in the Azure portal. It takes a couple of minutes to send data to the portal.

 To see logs inside Visual studio, open window called Application Insights Search. You find this window by clicking View->other Windows->Application Insights Search

Application Insights Search

It looks something like this

Click on the configuration wheel and choose your application insights Resource

Applicaiton Insights Resource

Then you'll see the windows like this

Application Insights search

To see the logs in the Azure portal, login to the portal and click on your Application Insights resource

Azure portal Application Insights

And click on Search

Search

Choose the correct filter for Local time and click on Apply. Besides the naming on this filter is probably not the best one. When you open this filter you see the right name "Time range" :-)

Local time filter

Now you can see the same information you just saw in the Visual Studio

The last important thing is, it si not very convenient to have Instrumentation Key hard coded into your code. It's truly that you are going to run your application in different environment with different Application Insights instances. The right place for this environment dependent variables are config file app.config or web.config.

Open the app.config file and add appSettings section. Paste the Application Insights Instrumentation Key like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <appSettings>
    <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="541b2793-939c-47c3-b62f-717d1b1420a9" />
  </appSettings>
</configuration>

Add reference to the System.Configuration dll. Right click on References in the visual studio

Add Reference

Search for system.configuration

Click on OK

Then open program.cs and modify it. Our program.cs looks like this

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using System;
using System.Configuration;
using System.ServiceProcess;


namespace WindowsServiceTemplate
{
    class Program
    {
        static void Main(string[] args)
        {
            var key = 
            ConfigurationManager.AppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"];
            TelemetryConfiguration.Active.InstrumentationKey = key;
            TelemetryConfiguration config = TelemetryConfiguration.Active;

            TelemetryClient aiClient = new TelemetryClient();
            try
            {
                aiClient.TrackTrace("Our service running just fine");
                StartProgram();
            }
            catch (Exception exception)
            {
                aiClient.TrackException(exception);
                throw;
            }
        }

        private static void StartProgram()
        {
            if (Environment.UserInteractive)
            {
                using (var service = new MyService())
                {
                    service.Start();
                    Console.WriteLine("Running, press any key to stop");
                    Console.ReadKey();
                }
            }
            else
            {
                ServiceBase.Run(new MyService());
            }
        }
    }
}

Also added aiClient.TrackException... where we send whole exception to the Application Insights.

Here is the link to the "home page" for this blog serie.


"Home page" for this blog serie

My Public Azure DevOps WindowsService project

WindowsServiceTemplate repository

What is Application Insights?