如何注入Application Insights代码以监视所有方法中的时序 [英] How to inject Application Insights code to monitor timing in all methods

查看:104
本文介绍了如何注入Application Insights代码以监视所有方法中的时序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF服务,可以通过这种方式使用Application Insights SDK测量时间.

I have a WCF Service where I measure timings with Application Insights SDK in this way.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [BasicHttpBindingServiceMetadataExchangeEndpoint]
    public class DMSWebService : IDMSWebService
    {
        public static readonly string LoggingPrefix = "DMSWebService";
        private TelemetryClient telemetry;

        //Defines if Application Insights must be enabled or not
        public Boolean EnableApplicationInsights { get; set; }

        //Application Insights Instrumentation Key
        public string ApplicationInsightsMonitoringKey { get; set; }

        //Constructor to get the property bag values only once.
        public DMSWebService()
        {
            InitializeApplicationInsights();
            telemetry= new TelemetryClient {InstrumentationKey = ApplicationInsightsMonitoringKey};
        }

        //Method to initialize ApplicationInsightSettings
        private void InitializeApplicationInsights()
        {
            bool enableApplicationInsights = false;
            using (var billingSite = BillingManagement.GetBillingSite())
            {
                enableApplicationInsights = Convert.ToBoolean(billingSite.WebApplication.GetProperty(Constants.WebApplicationSettings.EnableApplicationInsights));
                if(enableApplicationInsights) ApplicationInsightsMonitoringKey = billingSite.WebApplication.GetProperty(Constants.WebApplicationSettings.ApplicationInsightsKey);
            }

            EnableApplicationInsights = enableApplicationInsights;
        }
        #region Billing

        #region Archiving

        // GET
        public DMSServiceResult ArchiveBillCycle(string listItemId)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            using (var withDMSServiceResult = new WithDMSServiceResult(LoggingPrefix, "ArchiveBillCycle"))
            {
                try
                {
                    withDMSServiceResult.InputParameters["listItemId"] = listItemId;

                    var listItemIdAsInt = Convert.ToInt32(listItemId);

                    using (var billingSite = BillingManagement.GetBillingSite())
                    {
                        // HACK: Necessary to disable form digest validation, which we don't need.
                        using (var continueWithoutSPContext = new ContinueWithoutSPContext())
                        {
                            withDMSServiceResult.RequestSucceeded = BillingRepository.ArchiveBillCycle(billingSite.RootWeb, listItemIdAsInt);
                        }
                    }
                }
                catch (Exception ex)
                {
                    telemetry.TrackException(ex);
                    withDMSServiceResult.HandleError(ex);
                }

                stopwatch.Stop();
                var metrics = new Dictionary <string, double>{{"processingTime", stopwatch.Elapsed.TotalMilliseconds}};
                // Set up some properties:
                var properties = new Dictionary <string, string>{{"listItemId", withDMSServiceResult.InputParameters["listItemId"]}};
                if(EnableApplicationInsights) telemetry.TrackEvent("ArchiveBillCycle", properties, metrics);

                return withDMSServiceResult.Result;
            }
        }

        #endregion

如您所见,我在方法的开头启动了一个StopWatch,然后在方法的结尾将事件发送给Application Insights.

As you can see I start a StopWatch in the beginning of the method, and then I send the event to Application Insights at the end of the method.

对Web服务上的所有10种方法执行此操作并不重要,我已经做到了.

Doing this for all the 10 methods on the web service is not a big deal, I already did it.

但是,这些方法在其他类中调用实用程序方法,而找到瓶颈的唯一方法是测量每个方法.

However these methods call utilities methods in other classes, and the only way to find the bottleneck is to measure each of the methods.

您的建议是什么?

请注意trackEvent有一个属性字段,有时我会使用它,有时我只是发送空值.

Please note that the trackEvent has a properties field, which sometimes I use it, sometimes i Just send null.

Thx

推荐答案

查找AOP(面向方面的编程)框架(例如 PostSharp (付费)或使用类似确定这篇文章.

Look for an AOP (Aspect Oriented Programming) framework like PostSharp (paid) or use something like Aspectize or Castle DynamicProxy. There frameworks enables you to write some custom logic once and apply them at runtime or compile time to all specified methods. See this post for an example.

对于WCF,您可以更轻松地完成它,因为它内置了对呼叫拦截的支持,例如使用

For WCF you can do it easier as there is built in support for call interception using for example Message Inspectors.

这篇关于如何注入Application Insights代码以监视所有方法中的时序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆