简体   繁体   English

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

[英]How to inject Application Insights code to monitor timing in all methods

I have a WCF Service where I measure timings with Application Insights SDK in this way.我有一个 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

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.如您所见,我在方法的开头启动了一个 StopWatch,然后在方法的末尾将事件发送到 Application Insights。

Doing this for all the 10 methods on the web service is not a big deal, I already did it.对 Web 服务上的所有 10 个方法执行此操作没什么大不了的,我已经做到了。

However these methods call utilities methods in other classes, and the only way to find the bottleneck is to measure each of the methods.然而,这些方法调用其他类中的实用程序方法,找到瓶颈的唯一方法是测量每个方法。

What would be your suggestion?你的建议是什么?

Please note that the trackEvent has a properties field, which sometimes I use it, sometimes i Just send null.请注意 trackEvent 有一个属性字段,有时我使用它,有时我只发送空值。

Thx谢谢

Look for an AOP ( Aspect Oriented Programming ) framework like PostSharp (paid) or use something like Aspectize or Castle DynamicProxy .寻找 AOP(面向方面的编程)框架,如PostSharp (付费)或使用类似AspectizeCastle 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.有关示例,请参阅此帖子

For WCF you can do it easier as there is built in support for call interception using for example Message Inspectors .对于 WCF,您可以更轻松地做到这一点,因为它内置了对使用例如Message Inspectors 的调用拦截的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 配置Microsoft Application Insights以监视Windows服务 - Configuring Microsoft Application Insights to monitor a windows service 我在 Azure Function Monitor Logs 屏幕中看到了条目。 如何在 Application Insights 中找到它们? - i see entries in then Azure Function Monitor Logs screen. How do I find them in the Application Insights? 如何自定义 Application Insights - How to customize Application Insights 在Application Insights依赖关系跟踪中,如何设置依赖关系类型和结果代码? - In Application Insights dependency tracking, how to set Dependency Type and Result Code? 如何通过代码从 Azure 应用程序洞察中获取事务日志? - How to get transactional logs from Azure application insights via code? 如何跟踪应用程序中的所有方法 - How to trace all methods in an application 如何在使用Attribute装饰的方法中注入/生成管道代码? - How to inject/generate plumbing code into methods decorated with an Attribute? Application Insights 无代码附加状态监视器 V2 - Application Insights Codeless attach Status Monitor V2 如何在 ILogger 中刷新 Application Insights - How to Flush Application Insights in a ILogger 如何结合ILogger和应用程序见解 - How to combine ILogger and Application Insights
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM