如何配置Application Insights以从.NET 4.8应用程序发送遥测数据

huangapple go评论65阅读模式
英文:

How to configure Application Insights for sending telemetry from .net 4.8 application

问题

我似乎无法正确配置应用程序洞察力。也许我错过了一些非常重要的东西,或者它只是不能以我打算的方式完成。我有一个遗留的“Windows服务项目”,我正在尝试设置,以将一些遥测数据发送到应用洞察力,以获取一些异常日志和一些消息。

Azure已经为我设置了应用程序洞察力,但是当我配置我的C#项目时,我没有收到任何异常或消息。它只是一个Windows服务项目。

伪代码看起来像这样:

(不要在意奇怪的连接方式。这只是为了给你一个我尝试重构时的想法,当我有一些指标时)

static void Main(string[] args)
{

    var theService = new JobManagerService();
    theService.Start();
}
internal class JobManagerService
{
    private readonly List<JobManager> _jobs = new List<JobManager>();
    private TelemetryClient _tc;

    public JobManagerService()
    {
        InitializeSomething();
    }

    public void Start()
    {
        var config = TelemetryConfiguration.CreateDefault();
        config.InstrumentationKey = ConfigurationManager.AppSettings["JobManagerInstrumentationKey"]; // 正在弃用
        config.ConnectionString = $"InstrumentationKey={ConfigurationManager.AppSettings["JobManagerInstrumentationKey"]};IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/";
        config.TelemetryInitializers.Add(new AppInsightsJobManagerTelemetryInitializer());

        _tc = new TelemetryClient(config);
        _tc.TrackTrace($"Starting ApplicationInsights {nameof(TelemetryClient)} for {nameof(JobManagerService)}");
        AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventRaised;

        _jobs.Add(new JobManager(interval, job, App_Online, _tc));
        _tc.TrackTrace($"Job {job.Name} Initialized with interval {interval} ms");
        _tc.Flush();
    }
    private void UnhandledExceptionEventRaised(object sender, UnhandledExceptionEventArgs e)
    {
        _tc.TrackException((Exception)e.ExceptionObject);
    }
    private class AppInsightsJobManagerTelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            telemetry.Context.Properties["SystemGuid"] = Config.SystemConfiguration.SystemGuid.ToString();
            telemetry.Context.Properties["SystemName"] = Config.SystemConfiguration.SystemName.ToString();
            telemetry.Context.Properties["SystemType"] = Config.SystemConfiguration.SystemType.ToString();
        }
    }
}
internal class JobManager
{
    private readonly IJob _job;
    private readonly Timer _timer = new Timer();
    private readonly TelemetryClient _telemetryClient;

    public JobManager(int intInterval, IJob objJob, TelemetryClient telemetryClient)
    {
        if (intInterval > 60000) throw new ArgumentException("Interval cannot exceed 1 minute");
        _telemetryClient = telemetryClient;

        _job = objJob;

        _timer.Interval = intInterval;
        _timer.Enabled = true;
        _timer.Elapsed += mObjTimer_Elapsed;
    }
    private void mObjTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        try
        {
            _timer.Enabled = false;
            var _mObjJobCollection = new JobProviderService().ListByService(_job.Name);

            foreach (var objJob in _mObjJobCollection)
            {
                var objRunner = new JobRunner(objJob, _job);
                objRunner.Run();
            }
        }
        catch (Exception ex)
        {
            _telemetryClient.TrackException(ex);
        }
        finally
        {
            _telemetryClient.TrackDependency("Windows Service", _job.Name, _job.Name);
        }
    }
}

想法是每隔1分钟运行一些作业,并捕获异常,然后发送一些日志消息。

但出于某种原因,我在应用洞察力在线上没有收到**TrackException()TrackTrace()**的信息。仪器密钥和连接字符串是正确的,这应该足以让应用洞察力建立连接,但什么都没有显示出来。我已经尝试过applicationinsight.config文件,使用默认配置设置,但也没有任何好的效果。

ApplicationInsights没有出错。它只是没有发送数据。无论我在本地调试还是将其推送到生产环境中,都没有数据。

我漏掉了什么,或者应该如何正确配置和使用遥测?

英文:

I seem to be unable to configure application insight correctly.
Maybe I have missed something very important, or it just can't be done, the way I intent.
I have a legacy Windows Service project, that I'm trying to get set up, to send some telemetry to app insight, to get some logging of exception, and some messages.

App Insight has been set up for me in Azure, but I don't get any exceptions, or messages when I configure my C# project. Its just a

Windows Service project

The suedo code looks like this:

(Nevermind the wierd way it is plugged together.. Thats just to give you an idea of what I'm trying to refactor, when I have some metrics)

static void Main(string[] args)
{

    var theService = new JobManagerService();
    theService.Start();
}
internal class JobManagerService
    {
        private readonly List&lt;JobManager&gt; _jobs = new List&lt;JobManager&gt;();
        private TelemetryClient _tc;

        public JobManagerService()
        {
            InitializeSomething();
        }

        public void Start()
        {
            var config = TelemetryConfiguration.CreateDefault();
            config.InstrumentationKey = ConfigurationManager.AppSettings[&quot;JobManagerInstrumentationKey&quot;]; //IS BEING DEPRICATED
            config.ConnectionString = $&quot;InstrumentationKey={ConfigurationManager.AppSettings[&quot;JobManagerInstrumentationKey&quot;]};IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/&quot;;
            config.TelemetryInitializers.Add(new AppInsightsJobManagerTelemetryInitializer());

            _tc = new TelemetryClient(config);
            _tc.TrackTrace($&quot;Starting ApplicationInsights {nameof(TelemetryClient)} for {nameof(JobManagerService)}&quot;);
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventRaised;

            _jobs.Add(new JobManager(interval, job, App_Online, _tc));
            _tc.TrackTrace($&quot;Job {job.Name} Initialized with interval {interval} ms&quot;);
            _tc.Flush();
        }
        private void UnhandledExceptionEventRaised(object sender, UnhandledExceptionEventArgs e)
        {
            _tc.TrackException((Exception)e.ExceptionObject);
        }
        private class AppInsightsJobManagerTelemetryInitializer
        {
            public void Initialize(ITelemetry telemetry)
            {
                telemetry.Context.Properties[&quot;SystemGuid&quot;] = Config.SystemConfiguration.SystemGuid.ToString();
                telemetry.Context.Properties[&quot;SystemName&quot;] = Config.SystemConfiguration.SystemName.ToString();
                telemetry.Context.Properties[&quot;SystemType&quot;] = Config.SystemConfiguration.SystemType.ToString();
            }
        }
    }
internal class JobManager
    {
        private readonly IJob _job;
        private readonly Timer _timer = new Timer();
        private readonly TelemetryClient _telemetryClient;

        public JobManager(int intInterval, IJob objJob, TelemetryClient telemetryClient)
        {
            if (intInterval &gt; 60000) throw new ArgumentException(&quot;Interval cannot exceed 1 minute&quot;);
            //If intInterval &gt; 60 * 1000 Then Throw New ArgumentException(&quot;Interval cannot exceed 1 minute&quot;)
            _telemetryClient = telemetryClient;

            _job = objJob;

            //&#39; Load Jobs
            //_mObjJobCollection = new JobProviderService().ListByService(_job.Name);

            //&#39; Starts the loop that triggers mObjTimer_Elapsed on every &quot;interval&quot;
            _timer.Interval = intInterval;
            _timer.Enabled = true;
            _timer.Elapsed += mObjTimer_Elapsed;

           
        }
        private void mObjTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                _timer.Enabled = false;
                var _mObjJobCollection = new JobProviderService().ListByService(_job.Name);

                foreach (var objJob in _mObjJobCollection)
                {
                    var objRunner = new JobRunner(objJob, _job);
                    objRunner.Run();
                }
            }
            catch (Exception ex)
            {
                _telemetryClient.TrackException(ex);
            }
            finally
            {
                _telemetryClient.TrackDependency(&quot;Windows Service&quot;, _job.Name, _job.Name);
            }
        }
    }

The idea is that some jobs get run every 1 minute, and I want to catch exceptions, and just send some log-messages.

But for some reason I don't get the TrackException() or TrackTrace() in app insights online
The Instrumenentation key and Connectionstring is correct, which should be enough for app insight to establish a connection, but nothing shows up.
I've experimentented with applicationinsight.config file, using a default configuration setup, which doesn't do anything good either.

ApplicationInsights does break.
It just doesn&#39;t send data. Not when I debug locally, or when I push it to production.

What am I missing, or what should be the correct way to configure, and use telemetry?

答案1

得分: 1

看起来问题并不是我以为的那样。

配置本身是正确的,但客户端的 Application Insights 配置不正确。

Application Insights SDK NuGet 包提供多种安装选项,主要有 'Microsoft.ApplicationInsights.Web' 和 'Microsoft.ApplicationInsights.WorkerService'。

在我的情况下,安装了 Web 包,导致我的 applicationInsights.config 文件混乱不堪。

删除 applicationInsights.config 文件,卸载 Application Insights NuGet 包,然后重新安装 'Microsoft.ApplicationInsights.WorkerService',生成了一个新的默认 applicationInsights.config 文件,并且数据开始传输了。

这花了一些时间来弄清楚。
但希望这能帮助未来的读者摆脱我的苦恼。

从文档中弄清楚这个 Web/WorkerService 区别对我来说并不容易。
Tobias Zimmergren 表示大声致敬。

英文:

It seems the problem, was not what I thought it was.

Configuration as such,was correct, but client side Application Insights was not set up correctly..

Appplication Insights SDK nuget packages, comes in a variety of installations
primarily
'Microsoft.ApplicationInsights.Web' and'Microsoft.ApplicationInsights.WorkerService'

In my case, the Web package had been installed, which twarted my applicationInsights.config file to a clustered mess.

Deleting applicationInsights.config file, UNinstall Application Insights nuget package, and re-installing 'Microsoft.ApplicationInsights.WorkerService' made en new default applicationInsights.config file, and data started coming through.

That took some time to figure out.
But hopefully this will help some future reader from my agony.

This Web/WorkerService distinction was not easy for me to figure out from the documentation.
BIG SHOUT OUT TO:
Tobias Zimmergren

答案2

得分: 0

我至少能想到一种可能引起此问题的情景。如果发生未处理的异常,telemetryClient 将不会被刷新,从而导致在应用程序终止之前无法发送遥测数据。

此外,请注意,如果您调用 Flush(),需要添加一些延迟,因为该过程是异步的:

_tc.Flush();
Thread.Sleep(2000);

或者使用 FlushAsync

await _tc.FlushAsync(CancellationToken.None);

请参阅此问题,了解使用 Thread.Sleep 与调用 FlushAsync 之间的需要区分情况。

最后,在应用程序终止之前,请确保在所有路径上刷新遥测数据。根据所示的代码,很难确定是否已经这样做,特别是考虑到您的注释 (Nevermind the wierd way it is plugged together.. [..])。

英文:

I can think of at least one scenario that can cause the issue. If an unhandled exception occurs the telemetryClient is not flushed, preventing telemetry from being send before the application is terminated.

Also, do mind that if you do call Flush() you need to add a little delay since the process is async:

_tc.Flush();
Thread.Sleep(2000);

or use FlushAsync:

await _tc.FlushAsync(CancellationToken.None);

See this issue regarding the need to use Thread.Sleep versus calling FlushAsync.

Finally, make sure to flush the telemetry on all paths before the application is terminated. Given the code as shown it is hard to tell this is the case, especially given your comment (Nevermind the wierd way it is plugged together.. [..])

答案3

得分: 0

这个图表展示了应用洞察的工作原理。来自 Microsoft Learn 网站。

根据我的经验,这三个方法中应该有一个是有效的。

  1. 检查是否能在控制台中看到日志。
  2. 确保本地身份验证已启用。应用洞察 >> 属性 >> 本地身份验证。

如果设置为禁用,您应该能够访问应用洞察和应用洞察工作区。您可以在应用洞察概述页面上看到工作区名称。

首先,您需要检查是否能在控制台中看到遥测数据,如果是,则问题可能出在门户上配置的 AppInsight。

  1. 尝试使用此 PowerShell 脚本向应用洞察发送可用性消息。

PowerShell 脚本链接

希望对您有帮助。

英文:

This diagram shows how application insights work. Taken from microsoft learn website.

如何配置Application Insights以从.NET 4.8应用程序发送遥测数据

Based on my experience one of this three should work.

  1. Check if you are able to see logs in Console.
  2. Make sure local authentication is set to Enabled. Application Insights >> properties >> Local Authentication.

如何配置Application Insights以从.NET 4.8应用程序发送遥测数据

If its set to disabled, you should have access to Application Insights and Application insights workspace.
You can see workspace name on overview page of Application insights.

First you need to check if you are able to see Telemetry in console, if yes issue could be with AppInsight configured on portal.

  1. Try sending an availability message to your application insights using this powershell script.

https://learn.microsoft.com/en-us/troubleshoot/azure/azure-monitor/app-insights/investigate-missing-telemetry#powershell-script-send-availability-test-result

Hope this works for you.

huangapple
  • 本文由 发表于 2023年5月26日 15:33:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定