Skip to content

Provides the ability to collect telemetry with ApplicationInsights for PC app

License

Notifications You must be signed in to change notification settings

nishy2000/nsTelemetry

Repository files navigation

nsTelemetry (NishySoftware.Telemetry.ApplicationInsights)

Click here for Japanese page (日本語ページはこちら)

Development status

Build Status (develop) Build Status (master)

Downloads NuGet NuGet (pre) Release License

Issues Issues Pull Requests Pull Requests

About

This library provides PC apps with the ability to send telemetry information to measure PC app usage and exceptions. The destination for the telemetry information in this library is Azure Application Insight. The library wraps the API of ApplicationInsights to make it easy to use from PC apps. The PC apps are intended for Windows and Linux.

Telemetry Graph example Example graph of the app usage timeline in Azure Application Insights

License

This library is under the Apache-2.0 License.

Installation

Install NuGet package(s).

PM> Install-Package NishySoftware.Telemetry.ApplicationInsights

How to use

nsTelemetry (NishySoftware.Telemetry.ApplicationInsights)

This library provides a static Telemetry class and an ITelemetry interface. All public methods of the Telemetry class are exposed as static methods. The Telemetry class allows for overall configuration and instantiation of the ITelemetry interface. The ITelemetry interface can be used to configure telemetry data and send telemetry.

Prepare

  1. Get the InstrumentationKey from Azure Portal
    1. If you don't have an Azure account yet, go to the Azure portal and create an account with an active subscription. Create an account for free.
    2. Create an Application Insights resource in the Azure portal. For more information, please refer to Microsoft's website.
    3. Get the InstrumentationKey displayed in the "Overview" pane of the newly created resource page.
  2. Install this nuget library (NisySoftware.Telemetry.ApplicationInsights) in the target app project.
  3. Once the project is built, the ApplicationInsights.config file will be added to the project.
  4. Set the InstrumentKey obtained from the Azure portal to the content of the InstrumentKey tag in the ApplicationInsights.config file. If you do not want to set the InstrumentationKey in the ApplicationInsights.config file, you can specify it in the source code.

Implementation

  1. Setup the global common telemetry data (properties/metrics) if necessary.
  2. If the InstrumentationKey has not been set in the ApplicationInsights.config file, set the InstrumentationKey using SetInstrumentationKey().
  3. Create an instance of ITelemetry.
  4. Setup the global custom telemetry data (properties/metrics) if necessary.
  5. Set the DeveloperMode with EnableDeveloperMode() if necessary.
  6. Send telemetry using the TrackEvent() / TrackPageView() / TrackException() methods of the ITelemetry interface.

Example

namespace nsTelemetryAI.Sample
{
    using NishySoftware.Telemetry;
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    class Program
    {
        #region Fields
        DateTime _startupDateTime = DateTime.UtcNow;
        bool _sentEventExit = false;
        #endregion Fields

        #region Properties

        #region Telemetry
        static ITelemetry _telemetry;
        public static ITelemetry Telemetry
        {
            get
            {
                return LazyInitializer.EnsureInitialized<ITelemetry>(ref _telemetry, () =>
                {
                    // [en] Setting TelemetryDataFlags takes time the first time, so set it asynchronously.
                    Task.Run(() =>
                    {
                        // [en] Setup common global properties
                        NishySoftware.Telemetry.ApplicationInsights.Telemetry.CommonDataKinds = TelemetryDataKinds.All;
                    });

                    // [en] If you do not place the InstrumentationKey in ApplicationInsights.config file,
                    // setup the InstrumentationKey using SetInstrumentationKey().

                    // NishySoftware.Telemetry.ApplicationInsights.Telemetry.SetInstrumentationKey("your InstrumentationKey");

                    // [en] Create an instance of the telemetry interface
                    var telemetry = NishySoftware.Telemetry.ApplicationInsights.Telemetry.CreateTelemetry();

                    // [en] Add custom global property if you need
                    var userDomainName = Environment.UserDomainName;
                    lock (telemetry.GlobalSyncObject)
                    {
                        var prop = telemetry.GlobalProperties;
                        if (!prop.ContainsKey("UserDomainName"))
                        {
                            prop.Add("UserDomainName", userDomainName);
                        }
                    }

                    // [en] When the debugger is attached to the process, the default of developer mode is true 
                    //      Otherwise, the developer mode default is false.
                    //      When developer mode is true, transmission mode default is synchronous mode.
                    //      Otherwise, transmission mode default is asynchronous mode.
                    //      For console apps where the process terminates in a short period of time, asynchronous communication is not enough to send the data by the time the app terminates, so true is recommended.
#if DEBUG
                    // [en] For the debug version, always use asynchronous transmission if you need.
                    //NishySoftware.Telemetry.ApplicationInsights.Telemetry.EnableDeveloperMode(false);
#endif
#if !DEBUG
                    // [en] For the release version, always use synchronous transmission if you need.
                    NishySoftware.Telemetry.ApplicationInsights.Telemetry.EnableDeveloperMode(true);
#endif

                    return telemetry;
                });
            }
        }
        #endregion

        #endregion Properties

        #region Methods
        void TrackEventStartup(string[] startupArgs)
        {
            _startupDateTime = DateTime.UtcNow;
            Telemetry.TrackEvent("App_" + "General" + "Startup",
                "Command", startupArgs.Length > 0 ? startupArgs[0] : null);
        }

        void TrackEventExit(int exitCode)
        {
            if (!this._sentEventExit)
            {
                this._sentEventExit = true;
                var exitDateTime = DateTime.UtcNow;
                double duration = (exitDateTime - _startupDateTime).TotalSeconds;
                Telemetry.TrackEvent("App_" + "General" + "Exit",
                    "Duration", duration,
                    "ExitCode", exitCode.ToString());
                Telemetry.Flush();
                // [en] Wait a bit after calling Telemetry.Flush()
                Thread.Sleep(1000);
            }
        }
        #endregion Methods


        static void Main(string[] args)
        {
            var program = new Program();

            program.TrackEventStartup(args);

            Console.WriteLine("Hello World!");

            program.TrackEventExit(Environment.ExitCode);
        }
    }
}

nsTelemetry API Reference

The API reference for nsTelemetryAI can be found in the nsTelemetry.md file and the nsTelemetryAI.md file. This nsTelemetry.md and nsTelemetryAI.md are written in both English [en] and Japanese [ja].

namespace : NishySoftware.Telemetry

namespace : NishySoftware.Telemetry.ApplicationInsights

Configuration file (ApplicationInsights.config)

nsTelemetry uses ApplicationInsights.config file as a configuration file. The specification of the ApplicationInsights.config file is slightly extended from the original specification of the ApplicationInsights.config file.

  • InstrumentationDevKey tag

    This tag is intended to be used during development. The value of this tag will be used in place of the value of the InstrumentationKey tag when in developer mode or when the debugger is attached.

  • StorageFolder property of ServerTelemetryChannel on a non-Windows environment,

When using ServerTelemetryChannel in a non-Windows environment, the StorageFolder property must be explicitly specified in the ApplicationInsights.config file. When using this library, the StorageFolder property no longer needs to be explicitly specified. If the StorageFolder property is not specified, it will be set to the appropriate value in this library.