如何注入 Application Insights 代码以监控所有方法的计时

Posted

技术标签:

【中文标题】如何注入 Application Insights 代码以监控所有方法的计时【英文标题】:How to inject Application Insights code to monitor timing in all methods 【发布时间】:2018-02-24 10:54:05 【问题描述】:

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

[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。

对 Web 服务上的所有 10 种方法都这样做没什么大不了的,我已经这样做了。

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

你有什么建议?

请注意,trackEvent 有一个属性字段,有时我使用它,有时我只是发送 null。

谢谢

【问题讨论】:

【参考方案1】:

寻找像 PostSharp(付费)这样的 AOP (Aspect Oriented Programming) 框架或使用像 Aspectize 或 Castle DynamicProxy 这样的框架。这些框架使您可以编写一些自定义逻辑,并在运行时或编译时将它们应用于所有指定的方法。示例见this post。

对于 WCF,您可以更轻松地做到这一点,因为它内置了对呼叫拦截的支持,例如使用 Message Inspectors。

【讨论】:

以上是关于如何注入 Application Insights 代码以监控所有方法的计时的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Pyspark 提取 Azure Application Insights 事件?

如何使用 WCF 中多个环境的检测密钥配置 Application Insights?

如何在 Application Insights 中获取 VMSS 的实例数?

如何从 Kusto.Explorer 查询我的 Application Insights 日志(分析)?

如何从 Analytics Application Insights 获取 Qna Maker“Q”?

使用Application Insights监控应用程序性能