为什么Application Insights会阻止我的员工角色启动?

时间:2017-09-20 18:39:37

标签: c# azure azure-worker-roles azure-cloud-services azure-application-insights

我有一个具有单个辅助角色的Azure云服务,每次都会部署,启动和运行,但我遇到了一些我想用Application Insights诊断的间歇性问题。我按照this article以及here的说明进行操作。

安装了块包并添加了一行代码之后,我在调试和发布模式下在本地运行了云服务,并且能够看到向Application Insights资源报告的AI信息。所以我将其打包并将新配置上传到我的云服务。

但是从云端开始,工作者角色实际上不会启动 - 它会进入循环死亡螺旋,而在“诊断和解决问题”刀片中我会得到以下错误的变体,总是关于“System.Threading” .AsyncLocal'1'“并且无法加载RoleEntryPoint。 this article之后并没有对事情有所了解,因为错误几乎告诉我为什么它会继续回收,但没有任何线索可以解决这个问题。

  

生产 - WebReportDownloader_IN_0:BusyRole   等待角色启动...无法加载角色入口点。 System.TypeLoadException:无法从程序集'mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'加载类型'System.Threading.AsyncLocal`1'。位于Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.Initialize(TelemetryConfiguration配置,TelemetryModules模块,String serializedConfiguration)的Microsoft.ApplicationInsights.Extensibility.SdkInternalOperationsMonitor.Exit(),位于WebReportDownloader的Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.get_Active()处。 C:\ Users \ User \ Source \ Repos \ Program \ WebReportDownloader \ WebReportDownloader.cs中的ctor():第21行---内部异常堆栈跟踪结束---在System.RuntimeTypeHandle.CreateInstance(RuntimeType类型,布尔值publicOnly, System.RuntimeType.CreateInstanceSlow中的布尔值noCheck,Boolean& canBeCached,RuntimeMethodHandleInternal& ctor,Boolean& bNeedSecurityCheck)(System_RuntimeType.CreateInstanceDefaultCtor中的布尔值publicOnly,Boolean fillCheckThis,Boolean fillCache,StackCrawlMark& stackMark)布尔值publicOnly,布尔值skipCheckThis,布尔值fillCache ,StackCrawlMark& stackMark)a System.Activator.CreateInstance(Type type,Boolean nonPublic)位于Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetRoleEntryPoint(Assembly entryPointAssembly)的System.Activator.CreateInstance(Type type),位于Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.CreateRoleEntryPoint(RoleType roleTypeEnum) )在Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.InitializeRoleInternal(RoleType roleTypeEnum)[2017-09-14T15:28:21Z]最后退出时间:[2017/09 / 14,15:28:21.944]。最后退出代码:0。

通常我可以从搜索异常和/或细节中得到足够的提示,但这次我找不到任何类似于我的问题的东西。我可以猜到的是,虽然我的配置很小但很关键,但是根据我上面链接的说明,我无法确定自己离开轨道的位置。

我的ServiceConfiguration.Cloud文件......

    <?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="WebReportDownloader" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="4" osVersion="*" schemaVersion="2015-04.2.6">
  <Role name="WebReportDownloader">
    <Instances count="2" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled" value="true" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername" value="admin" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword" value="ENCRYPTEDVALUE" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration" value="2018-09-01T23:59:59.0000000-04:00" />
      <Setting name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.Enabled" value="true" />
      <Setting name="APPINSIGHTS_INSTRUMENTATIONKEY" value="KEYVALUE" />
    </ConfigurationSettings>
    <Certificates>
      <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="847EEDE0084CF57A5A774CAE9E700713726CC856" thumbprintAlgorithm="sha1" />
    </Certificates>
  </Role>
</ServiceConfiguration>

我的ApplicationInsights.config ......

<?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.AzureWebAppRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer"/>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer"/>
    </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. 
        This is only applicable if Profiler is installed via either StatusMonitor or Azure Extension.
        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>
                <Add>localhost</Add>
                <Add>127.0.0.1</Add>
            </ExcludeComponentCorrelationHttpHeadersOnDomains>
        </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.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>
    </TelemetryModules>
    <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"/>
<!-- 
    Learn more about Application Insights configuration with ApplicationInsights.config here: 
    http://go.microsoft.com/fwlink/?LinkID=513840

    Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
  --></ApplicationInsights>

我的“OnStart()”方法实际设置了InstrumentationKey ......

public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;
            TelemetryConfiguration.Active.InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("APPINSIGHTS_INSTRUMENTATIONKEY");

            // For information on handling configuration changes
            // see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("WebReportDownloader has been started");

            return result;
        }

我很感激有任何见解(哈!)或任何人都可以提供的指导...

更新

通过进一步的实验,我确定每当我尝试直接调用Application Insights程序集时(例如在创建遥测客户端或直接设置ApplicationInsights资源键时)或者因为a而调用ApplicationInsight TraceListener时追踪下面的例外叫做

  

无法从程序集'mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'加载类型'System.Threading.AsyncLocal`1'。

如果我执行运行时检测,我可以获得一些基本的跟踪和日志到我的Insight资源,但是试图获得更多的东西仍然让我感到厌烦。

此外,我目前的目标是.NET 4.6.1(我之前忽略的信息)。

2 个答案:

答案 0 :(得分:3)

经过Azure支持的大量来回,我终于能够设置屏幕共享会话了。这位乐于助人的绅士几乎可以立即注意到这个问题:因为我的工作者角色项目的目标是.NET 4.6.1 ,所以ServiceConfiguration文件(.Cloud.cscfg和.Local.cscfg)需要是定位osFamily 5

VS17向导生成的默认值将其设置为osFamily = 4,如下所示......

.NET 4.5.2 configuration

然而,我需要让一切正常运行的目标是osFamily = 5,如下所示......

.NET 4.6.1 configuration

在实例化TelemetryClient时,一个小的更改允许Web角色正确部署。

答案 1 :(得分:0)

根据您的描述,我创建了我的Azure Cloud Service项目,并在.NET Framework 4.5上添加了单个Worker Role目标,然后安装了Microsoft.ApplicationInsights.WindowsServer 2.4.1并添加了您提到的用于设置检测密钥的代码,如下所示:

<强> WorkerRole.cs

public class WorkerRole : RoleEntryPoint
{
    private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
    private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);

    public override void Run()
    {
        Trace.TraceInformation("WorkerRoleB is running");

        try
        {
            this.RunAsync(this.cancellationTokenSource.Token).Wait();
        }
        finally
        {
            this.runCompleteEvent.Set();
        }
    }

    public override bool OnStart()
    {
        // Set the maximum number of concurrent connections
        ServicePointManager.DefaultConnectionLimit = 12;

        TelemetryConfiguration.Active.InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("APPINSIGHTS_INSTRUMENTATIONKEY");

        // For information on handling configuration changes
        // see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.

        bool result = base.OnStart();

        Trace.TraceInformation("WorkerRoleB has been started");

        return result;
    }

    public override void OnStop()
    {
        Trace.TraceInformation("WorkerRoleB is stopping");

        this.cancellationTokenSource.Cancel();
        this.runCompleteEvent.WaitOne();

        base.OnStop();

        Trace.TraceInformation("WorkerRoleB has stopped");
    }

    private async Task RunAsync(CancellationToken cancellationToken)
    {
        // TODO: Replace the following with your own logic.
        while (!cancellationToken.IsCancellationRequested)
        {
            Trace.TraceInformation("Working");
            await Task.Delay(1000);
        }
    }
}

部署到Azure Cloud Service后,它可以按预期工作,我可以从AI检索诊断数据,如下所示:

enter image description here

注意:正如Install the SDK in each project所述,您需要将ApplicationInsights.config文件设置为始终复制到输出目录。

此外,您可以参考quick start并在运行时检测您的应用以缩小此问题。此外,如果我遗漏了某些内容或您执行了其他特殊代码,您可以更新我的问题以解决此问题。