ASP.NET web siteniz için Application Insights yapılandırma

bu yordam ASP.NET web uygulamanızı Azure izleyici hizmetinin Application Insights özelliğine telemetri gönderecek şekilde yapılandırır. şirket içinde veya bulutta kendi ııs sunucularınızda barındırılan ASP.NET uygulamalar için geçerlidir.

Önkoşullar

Application Insights’ı ASP.NET web sitenize eklemek için şunu yapmanız gerekir:

Önemli

İzleme anahtarları üzerinde bağlantı dizeleri öneririz. Yeni Azure bölgeleri, izleme anahtarları yerine bağlantı dizelerinin kullanılmasını gerektirir .

Bir bağlantı dizesi, telemetri verilerinize ilişkilendirmek istediğiniz kaynağı tanımlar. Ayrıca, kaynağınızın telemetri için hedef olarak kullanacağı uç noktaları değiştirmenize de olanak tanır. Bağlantı dizesini kopyalamanız ve uygulamanızın koduna veya bir ortam değişkenine eklemeniz gerekir.

temel bir ASP.NET web uygulaması oluşturma

  1. Visual Studio 2019 ' i açın.
  2. dosya > yeni > Project seçin.
  3. ASP.NET Web uygulaması (.NET Framework) C#' ı seçin.
  4. Bir proje adı girin ve ardından Oluştur' u seçin.
  5. MVC > Oluştur' u seçin.

otomatik olarak Application Insights ekle

bu bölüm, şablon tabanlı ASP.NET web uygulamasına Application Insights otomatik olarak ekleme konusunda size kılavuzluk eder. ASP.NET web uygulaması projenizin içinden Visual Studio:

  1. ileri Project > ekle Application Insights Telemetri > Application Insights Sdk (yerel)' i seçin > > > .

  2. ApplicationInsights.config dosyasını açın.

  3. kapanış etiketinden önce </ApplicationInsights> , Application Insights kaynağınız için izleme anahtarını içeren bir satır ekleyin. izleme anahtarınızı, bu makalenin önkoşulların bir parçası olarak oluşturduğunuz yeni oluşturulan Application Insights kaynağının genel bakış bölmesinde bulabilirsiniz.

    <InstrumentationKey>your-instrumentation-key-goes-here</InstrumentationKey>
    
  4. NuGet paketleri > güncelleştirmelerini yönetmek Project seçin. sonra her bir Microsoft.ApplicationInsights NuGet paketini en son kararlı sürüme güncelleştirin.

  5. IIS Express seçerek uygulamanızı çalıştırın. temel bir ASP.NET uygulaması açılır. sitedeki sayfalara göz atarken telemetri Application Insights gönderilir.

Application Insights el ile ekle

bu bölüm, şablon tabanlı ASP.NET web uygulamasına Application Insights el ile ekleme konusunda size kılavuzluk eder. bu bölüm, ASP.NET Framework için standart MVC web uygulaması şablonunu temel alan bir web uygulaması kullandığınızı varsayar.

  1. aşağıdaki NuGet paketlerini ve bunların bağımlılıklarını projenize ekleyin:

  2. Bazı durumlarda ApplicationInsights.config dosyası sizin için otomatik olarak oluşturulur. Dosya zaten mevcutsa 4. adıma atlayın.

    Otomatik olarak oluşturulmadıysa, kendiniz oluşturmanız gerekir. Projenizdeki Global. asax dosyası olarak aynı düzeyde ApplicationInsights.config adlı yeni bir dosya oluşturun.

  3. Aşağıdaki XML yapılandırmasını yeni oluşturduğunuz dosyaya kopyalayın:

    <?xml version="1.0" encoding="utf-8"?>
    <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
     <TelemetryInitializers>
       <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector" />
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" />
       <Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
         <!-- Extended list of bots:
               search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
         <Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
       </Add>
       <Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" />
     </TelemetryInitializers>
     <TelemetryModules>
       <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
         <ExcludeComponentCorrelationHttpHeadersOnDomains>
           <!-- 
           Requests to the following hostnames will not be modified by adding correlation headers.         
           Add entries here to exclude additional hostnames.
           NOTE: this configuration will be lost upon NuGet upgrade.
           -->
           <Add>core.windows.net</Add>
           <Add>core.chinacloudapi.cn</Add>
           <Add>core.cloudapi.de</Add>
           <Add>core.usgovcloudapi.net</Add>
         </ExcludeComponentCorrelationHttpHeadersOnDomains>
         <IncludeDiagnosticSourceActivities>
           <Add>Microsoft.Azure.EventHubs</Add>
           <Add>Microsoft.Azure.ServiceBus</Add>
         </IncludeDiagnosticSourceActivities>
       </Add>
       <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
         <!--
         Use the following syntax here to collect additional performance counters:
    
         <Counters>
           <Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
           ...
         </Counters>
    
         PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
    
         NOTE: performance counters configuration will be lost upon NuGet upgrade.
    
         The following placeholders are supported as InstanceName:
           ??APP_WIN32_PROC?? - instance name of the application process  for Win32 counters.
           ??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
           ??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
         -->
       </Add>
       <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
         <!--
         Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider 
         with the following syntax:
    
         <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
           <ExcludedHeartbeatProperties>
             <Add>osType</Add>
             <Add>location</Add>
             <Add>name</Add>
             <Add>offer</Add>
             <Add>platformFaultDomain</Add>
             <Add>platformUpdateDomain</Add>
             <Add>publisher</Add>
             <Add>sku</Add>
             <Add>version</Add>
             <Add>vmId</Add>
             <Add>vmSize</Add>
             <Add>subscriptionId</Add>
             <Add>resourceGroupName</Add>
             <Add>placementGroupId</Add>
             <Add>tags</Add>
             <Add>vmScaleSetName</Add>
           </ExcludedHeartbeatProperties>
         </Add>
    
         NOTE: exclusions will be lost upon upgrade.
         -->
       </Add>
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" />
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" />
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
         <!--</Add>
       <Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">-->
       </Add>
       <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
         <Handlers>
           <!-- 
           Add entries here to filter out additional handlers: 
    
           NOTE: handler configuration will be lost upon NuGet upgrade.
           -->
           <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
           <Add>System.Web.StaticFileHandler</Add>
           <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
           <Add>System.Web.Optimization.BundleHandler</Add>
           <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
           <Add>System.Web.Handlers.TraceHandler</Add>
           <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
           <Add>System.Web.HttpDebugHandler</Add>
         </Handlers>
       </Add>
       <Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" />
       <Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" />
     </TelemetryModules>
     <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
     <TelemetrySinks>
       <Add Name="default">
         <TelemetryProcessors>
           <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
           <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
           <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
             <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
             <ExcludedTypes>Event</ExcludedTypes>
           </Add>
           <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
             <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
             <IncludedTypes>Event</IncludedTypes>
           </Add>
         </TelemetryProcessors>
         <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
       </Add>
     </TelemetrySinks>
     <!-- 
       Learn more about Application Insights configuration with ApplicationInsights.config here: 
       http://go.microsoft.com/fwlink/?LinkID=513840
     -->
     <InstrumentationKey>your-instrumentation-key-here</InstrumentationKey>
    </ApplicationInsights>
    
  4. kapanış etiketinden önce </ApplicationInsights> , Application Insights kaynağınız için izleme anahtarınızı ekleyin. izleme anahtarınızı, bu makalenin önkoşulların bir parçası olarak oluşturduğunuz yeni oluşturulan Application Insights kaynağının genel bakış bölmesinde bulabilirsiniz.

    <InstrumentationKey>your-instrumentation-key-goes-here</InstrumentationKey>
    
  5. ApplicationInsights.config dosyası ile projenizin aynı düzeyinde, Aihandleerrorattribute. cs adlı yeni bir C# dosyası ile ErrorHandler adlı bir klasör oluşturun. Dosyanın içeriği şöyle görünür:

    using System;
    using System.Web.Mvc;
    using Microsoft.ApplicationInsights;
    
    namespace WebApplication10.ErrorHandler //namespace will vary based on your project name
    {
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
        public class AiHandleErrorAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
                {
                    //If customError is Off, then AI HTTPModule will report the exception
                    if (filterContext.HttpContext.IsCustomErrorEnabled)
                    {   
                        var ai = new TelemetryClient();
                        ai.TrackException(filterContext.Exception);
                    } 
                }
                base.OnException(filterContext);
            }
        }
    }
    
    
  6. App_Start klasöründe, filterconfig. cs dosyasını açın ve örnekle eşleşecek şekilde değiştirin:

    using System.Web;
    using System.Web.Mvc;
    
    namespace WebApplication10 //Namespace will vary based on project name
    {
        public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new ErrorHandler.AiHandleErrorAttribute());
            }
        }
    }
    
  7. Web.config zaten güncelleştirilirse, bu adımı atlayın. Aksi takdirde, dosyayı aşağıdaki gibi güncelleştirin:

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      https://go.microsoft.com/fwlink/?LinkId=301880
      -->
    <configuration>
      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2" />
        <!-- Code added for Application Insights start -->
        <httpModules>
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
        <!-- Code added for Application Insights end -->
      </system.web>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
            <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
          </dependentAssembly>
          <!-- Code added for Application Insights start -->
          <dependentAssembly>
            <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
          </dependentAssembly>
          <!-- Code added for Application Insights end -->
        </assemblyBinding>
      </runtime>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <!-- Code added for Application Insights start -->
        <modules>
          <remove name="TelemetryCorrelationHttpModule" />
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="managedHandler" />
          <remove name="ApplicationInsightsWebTracking" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
        <!-- Code added for Application Insights end -->
      </system.webServer>
    </configuration>
    
    

Sunucu tarafı uygulama izlemeyi başarıyla yapılandırdınız. web uygulamanızı çalıştırırsanız, telemetri Application Insights ' de görünme başlamanızı görürsünüz.

İstemci tarafı izleme ekleme

Önceki bölümler, sunucu tarafı izlemeyi otomatik olarak ve el ile yapılandırmak için yöntemler hakkında rehberlik sağlamaktadır. İstemci tarafı izleme eklemek için, istemci tarafı JavaScript SDK 'sınıkullanın. Sayfanın HTML kapatma etiketinden önce bir JavaScript kod parçacığı ekleyerek herhangi bir Web sayfasının istemci tarafı işlemlerini izleyebilirsiniz </head> .

Kod parçacığını her HTML sayfasının üstbilgisine el ile eklemek mümkün olsa da, kod parçacığını birincil sayfaya eklemenizi öneririz. Bu eylem, parçacığı bir sitenin tüm sayfalarına ekleyecektir.

bu makaleden şablon tabanlı ASP.NET MVC uygulaması için, düzenlemeniz gereken dosya _Layout. cshtml' dir. Bunu, paylaşılan Görünümler altında bulabilirsiniz > . İstemci tarafı izleme eklemek için _Layout. cshtml dosyasını açın ve Istemci tarafı JavaScript SDK yapılandırması hakkında makalesindeki kod parçacığı tabanlı kurulum yönergelerini izleyin.

Sorun giderme

geçerli Visual Studio 2019 sürümünde bilinen bir sorun var: izleme anahtarının bir kullanıcı gizliliğine depolanması, .NET Framework tabanlı uygulamalar için kopuk. Bu hatayı çözmek için anahtarın sonunda applicationinsights.config dosyasına sabit olarak kodlanmış olması vardır. Bu makale, bu sorunu tamamen önlemek için tasarlandı, Kullanıcı gizli dizileri kullanmayın.

Açık kaynaklı SDK

Kodu okuyun ve koda katkıda bulunun.

En son güncelleştirmeler ve hata düzeltmeleri için sürüm notlarına bakın.

Sonraki adımlar