监视经典 Windows 桌面应用中的使用情况和性能Monitoring usage and performance in Classic Windows Desktop apps

在 Azure 和其他云中本地托管的应用程序都可以利用 Application Insights。Applications hosted on premises, in Azure, and in other clouds can all take advantage of Application Insights. 唯一限制是需要允许与 Application Insights 服务通信The only limitation is the need to allow communication to the Application Insights service. 若要监视通用 Windows 平台 (UWP) 应用程序,我们建议使用 Visual Studio App CenterFor monitoring Universal Windows Platform (UWP) applications, we recommend Visual Studio App Center.

将遥测从经典 Windows 应用程序发送到 Application InsightsTo send telemetry to Application Insights from a Classic Windows application

  1. Azure 门户中,创建 Application Insights 资源In the Azure portal, create an Application Insights resource.

  2. 获取检测密钥的副本。Take a copy of the Instrumentation Key.

  3. 在 Visual Studio 中,编辑应用项目的 NuGet 包,并添加 Microsoft.ApplicationInsights.WindowsServer。In Visual Studio, edit the NuGet packages of your app project, and add Microsoft.ApplicationInsights.WindowsServer. (或者,如果只需要基本 API,而无需标准遥测收集模块,则选择 Microsoft.ApplicationInsights。)(Or choose Microsoft.ApplicationInsights if you just want the base API, without the standard telemetry collection modules.)

  4. 在代码中设置检测密钥:Set the instrumentation key either in your code:

    TelemetryConfiguration.Active.InstrumentationKey = " 你的密钥 ";TelemetryConfiguration.Active.InstrumentationKey = " your key ";

    或在 ApplicationInsights.config 中设置检测密钥(如果已安装标准遥测包之一):or in ApplicationInsights.config (if you installed one of the standard telemetry packages):

    <InstrumentationKey>你的密钥</InstrumentationKey><InstrumentationKey>your key</InstrumentationKey>

    如果使用 ApplicationInsights.config,请确保它在解决方案资源管理器中的属性设置为“生成操作”=“内容”、“复制到输出目录”=“复制”。If you use ApplicationInsights.config, make sure its properties in Solution Explorer are set to Build Action = Content, Copy to Output Directory = Copy.

  5. 使用 API 发送遥测。Use the API to send telemetry.

  6. 运行应用,并在 Azure 门户中创建的资源中查看遥测。Run your app, and see the telemetry in the resource you created in the Azure portal.

示例代码Example code

using Microsoft.ApplicationInsights;

    public partial class Form1 : Form
    {
        private TelemetryClient tc = new TelemetryClient();
        ...
        private void Form1_Load(object sender, EventArgs e)
        {
            // Alternative to setting ikey in config file:
            tc.InstrumentationKey = "key copied from portal";

            // Set session data:
            tc.Context.Session.Id = Guid.NewGuid().ToString();
            tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString();

            // Log a page view:
            tc.TrackPageView("Form1");
            ...
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;

            if (tc != null)
            {
                tc.Flush(); // only for desktop apps

                // Allow time for flushing:
                System.Threading.Thread.Sleep(1000);
            }
            base.OnClosing(e);
        }

替代计算机名称的存储Override storage of computer name

默认情况下,此 SDK 将收集并存储发出遥测的系统的计算机名称。By default this SDK will collect and store the computer name of the system emitting telemetry.

计算机名由 Application Insights 旧的企业(按节点)定价层用于内部计费。Computer name is used by Application Insights Legacy Enterprise (Per Node) pricing tier for internal billing purposes. 默认情况下,如果使用遥测初始值设定项替代 telemetry.Context.Cloud.RoleInstance,则将发送一个单独的属性 ai.internal.nodeName,该属性仍将包含计算机名值。By default if you use a telemetry initializer to override telemetry.Context.Cloud.RoleInstance, a separate property ai.internal.nodeName will be sent which will still contain the computer name value. 此值不会与 Application Insights 遥测数据一起存储,而是在内部引入时使用,以允许向后兼容基于旧节点的计费模型。This value will not be stored with your Application Insights telemetry, but is used internally at ingestion to allow for backwards compatibility with the legacy node-based billing model.

如果你使用的是旧的企业(按节点)定价层,并且只需要替代计算机名的存储,请使用遥测初始值设定项:If you are on the Legacy Enterprise (Per Node) pricing tier and simply need to override storage of the computer name, use a telemetry Initializer:

按如下所示编写自定义 TelemetryInitializer。Write custom TelemetryInitializer as below.

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

namespace CustomInitializer.Telemetry
{
    public class MyTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance))
            {
                // Set custom role name here. Providing an empty string will result
                // in the computer name still be sent via this property.
                  telemetry.Context.Cloud.RoleInstance = "Custom RoleInstance";
            }
        }
    }
}

在以下设置检测密钥的 Program.cs Main() 方法中实例化初始化程序:Instantiate the initializer in the Program.cs Main() method below setting the instrumentation key:

 using Microsoft.ApplicationInsights.Extensibility;
 using CustomInitializer.Telemetry;

   static void Main()
        {
            TelemetryConfiguration.Active.InstrumentationKey = "{Instrumentation-key-here}";
            TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
            //...
        }

替代计算机名的传输Override transmission of computer name

如果你使用的不是旧的企业(按节点)定价层,并且想要完全阻止发送包含计算机名的任何遥测,则需要使用遥测处理器。If you aren't on the Legacy Enterprise (Per Node) pricing tier and wish to completely prevent any telemetry containing computer name from being sent, you need to use a telemetry processor.

遥测处理器Telemetry processor

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


namespace WindowsFormsApp2
{
    public class CustomTelemetryProcessor : ITelemetryProcessor
    {
        private readonly ITelemetryProcessor _next;

        public CustomTelemetryProcessor(ITelemetryProcessor next)
        {
            _next = next;
        }

        public void Process(ITelemetry item)
        {
            if (item != null)
            {
                item.Context.Cloud.RoleInstance = string.Empty;
            }

            _next.Process(item);
        }
    }
}

在以下设置检测密钥的 Program.cs Main() 方法中实例化遥测处理器:Instantiate the telemetry processor in the Program.cs Main() method below setting the instrumentation key:

using Microsoft.ApplicationInsights.Extensibility;

namespace WindowsFormsApp2
{
    static class Program
    {
        static void Main()
        {
            TelemetryConfiguration.Active.InstrumentationKey = "{Instrumentation-key-here}";
            var builder = TelemetryConfiguration.Active.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
            builder.Use((next) => new CustomTelemetryProcessor(next));
            builder.Build();
            //...
        }
    }
}

备注

尽管技术上你可以使用如上所述的遥测处理器(即使你使用的是旧的企业(按节点)定价层),但这将由于无法针对每个节点定价区分节点而导致超额计费。While you can technically use a telemetry processor as described above even if you are on the Legacy Enterprise (Per Node) pricing tier, this will result in the potential for over-billing due to the inability to properly distinguish nodes for per node pricing.

后续步骤Next steps