internal static void RegisterSystemCounters(MetricsContext context)
        {
            context.Register("Available RAM", Unit.MegaBytes, "Memory", "Available MBytes", tags: "memory");
            context.Register("Free System Page Table Entries", Unit.Custom("entries"), "Memory", "Free System Page Table Entries", tags: "memory");
            context.Register("Pages Input/sec", Unit.Custom("pages/s"), "Memory", "Pages Input/sec", tags: "memory");
            context.Register("Pages/sec", Unit.Custom("pages/s"), "Memory", "Pages/sec", tags: "memory");
            context.Register("Pool Nonpaged MBytes", Unit.MegaBytes, "Memory", "Pool Nonpaged Bytes", derivate: v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Pool Paged MBytes", Unit.MegaBytes, "Memory", "Pool Paged Bytes", derivate: v => v / (1024 * 1024.0), tags: "memory");

            context.Register("CPU Usage", Unit.Custom("%"), "Processor", "% Processor Time", TotalInstance, tags: "cpu");
            context.Register("Interrupts / sec", Unit.Custom("interrupts/s"), "Processor", "Interrupts/sec", TotalInstance, tags: "cpu");
            context.Register("% Interrupt time", Unit.Custom("%"), "Processor", "% Interrupt Time", TotalInstance, tags: "cpu");
            context.Register("% User Timer", Unit.Custom("%"), "Processor", "% User Time", TotalInstance, tags: "cpu");
            context.Register("% Privileged Timer", Unit.Custom("%"), "Processor", "% Privileged Time", TotalInstance, tags: "cpu");
            context.Register("% DPC Time", Unit.Custom("%"), "Processor", "% DPC Time", TotalInstance, tags: "cpu");

            context.Register("Logical Disk Avg. sec/Read", Unit.Custom("ms"), "LogicalDisk", "Avg. Disk sec/Read", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Logical Disk Avg. sec/Write", Unit.Custom("ms"), "LogicalDisk", "Avg. Disk sec/Write", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Logical Disk Transfers/sec", Unit.Custom("Transfers"), "LogicalDisk", "Disk Transfers/sec", TotalInstance, tags: "disk");
            context.Register("Logical Disk Writes/sec", Unit.Custom("kb/s"), "LogicalDisk", "Disk Reads/sec", TotalInstance, f => f / 1024.0, tags: "disk");
            context.Register("Logical Disk Reads/sec", Unit.Custom("kb/s"), "LogicalDisk", "Disk Writes/sec", TotalInstance, f => f / 1024.0, tags: "disk");

            context.Register("Physical Disk Avg. sec/Read", Unit.Custom("ms"), "PhysicalDisk", "Avg. Disk sec/Read", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Physical Disk Avg. sec/Write", Unit.Custom("ms"), "PhysicalDisk", "Avg. Disk sec/Write", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Physical Disk Transfers/sec", Unit.Custom("Transfers"), "PhysicalDisk", "Disk Transfers/sec", TotalInstance, tags: "disk");
            context.Register("Physical Disk Writes/sec", Unit.Custom("kb/s"), "PhysicalDisk", "Disk Reads/sec", TotalInstance, f => f / 1024.0, tags: "disk");
            context.Register("Physical Disk Reads/sec", Unit.Custom("kb/s"), "PhysicalDisk", "Disk Writes/sec", TotalInstance, f => f / 1024.0, tags: "disk");
        }
        internal ShuffleClientMetrics(TaskAttemptID reduceId, JobConf jobConf)
        {
            this.numCopiers = jobConf.GetInt(MRJobConfig.ShuffleParallelCopies, 5);
            MetricsContext metricsContext = MetricsUtil.GetContext("mapred");

            this.shuffleMetrics = MetricsUtil.CreateRecord(metricsContext, "shuffleInput");
            this.shuffleMetrics.SetTag("user", jobConf.GetUser());
            this.shuffleMetrics.SetTag("jobName", jobConf.GetJobName());
            this.shuffleMetrics.SetTag("jobId", reduceId.GetJobID().ToString());
            this.shuffleMetrics.SetTag("taskId", reduceId.ToString());
            this.shuffleMetrics.SetTag("sessionId", jobConf.GetSessionId());
            metricsContext.RegisterUpdater(this);
        }
        static double GetHighestSequenceNumber(string sequenceKey, MetricsContext metricsContext, string type)
        {
            var data = metricsContext.DataProvider.CurrentMetricsData;

            var matchingType = data.Flatten()
                               .Gauges.Where(g => g.Tags.Contains(type));

            var receiveSideLinkStateForThisQueue = matchingType
                                                   .Where(g => g.Name == sequenceKey)
                                                   .Select(g => g.Value);

            return(receiveSideLinkStateForThisQueue.Max());
        }
Example #4
0
        public Form1()
        {
            InitializeComponent();

            dataManager = new FullDataManager();

            using (var context = new MetricsContext())
            {
                context.Database.EnsureCreated();
            }

            savedData = new DataToSave();
        }
        static double GetNumberOfInFlightMessages(string sequenceKey, MetricsContext receiveStateContext, MetricsContext sendStateContext)
        {
            var receiveGauge =
                receiveStateContext.DataProvider.CurrentMetricsData.Gauges.First(g => g.Name == sequenceKey);
            var sentGauge =
                sendStateContext.DataProvider.CurrentMetricsData.Gauges.FirstOrDefault(g => g.Name == sequenceKey);

            if (sentGauge == null)
            {
                return(0);
            }
            return(sentGauge.Value - receiveGauge.Value);
        }
        public void TestFlushWithDefaultDimensionDefined()
        {
            MetricsContext metricsContext = new MetricsContext();

            metricsContext.DefaultDimensions.Dimensions.Add("foo", "bar");
            _metricsLogger = new MetricsLogger(_environment, metricsContext, _logger);
            string logGroup = "TestLogGroup";

            _environment.LogGroupName.Returns(logGroup);
            _metricsLogger.Flush();

            ExpectDimension("foo", "bar");
            ExpectDimension("LogGroup", null);
        }
Example #7
0
 static void GetComputerUsageData(string computerName)
 {
     using (var _ctx = new MetricsContext())
     {
         var metrics = _ctx.ComputerMetrics.FirstOrDefault(p => p.Name == computerName);
         if (metrics != null)
         {
             foreach (var usageData in metrics.UsageDatas)
             {
                 Console.WriteLine(usageData.CpuUsage);
             }
         }
     }
 }
Example #8
0
        /// <summary>
        /// Adds default dimensions and properties from the specified environment into the specified metrics context.
        /// </summary>
        /// <param name="context">the context to configure with environment information</param>
        private void ConfigureContextForEnvironment(MetricsContext context)
        {
            if (context.HasDefaultDimensions)
            {
                return;
            }

            var defaultDimensions = new DimensionSet();

            defaultDimensions.AddDimension("ServiceName", _environment.Name);
            defaultDimensions.AddDimension("ServiceType", _environment.Type);
            context.DefaultDimensions = defaultDimensions;
            _environment.ConfigureContext(context);
        }
        public LocalJobRunnerMetrics(JobConf conf)
        {
            string sessionId = conf.GetSessionId();

            // Initiate JVM Metrics
            JvmMetrics.Init("JobTracker", sessionId);
            // Create a record for map-reduce metrics
            MetricsContext context = MetricsUtil.GetContext("mapred");

            // record name is jobtracker for compatibility
            metricsRecord = MetricsUtil.CreateRecord(context, "jobtracker");
            metricsRecord.SetTag("sessionId", sessionId);
            context.RegisterUpdater(this);
        }
Example #10
0
        public HttpServiceListener(IActivator activator, IWorker worker, IServiceEndPointDefinition serviceEndPointDefinition,
                                   ICertificateLocator certificateLocator, ILog log,
                                   IEnumerable <ICustomEndpoint> customEndpoints, IEnvironment environment,
                                   JsonExceptionSerializer exceptionSerializer,
                                   ServiceSchema serviceSchema,
                                   Func <LoadShedding> loadSheddingConfig,
                                   IServerRequestPublisher serverRequestPublisher,
                                   CurrentApplicationInfo appInfo
                                   )
        {
            ServiceSchema           = serviceSchema;
            _serverRequestPublisher = serverRequestPublisher;

            ServiceEndPointDefinition = serviceEndPointDefinition;
            Worker              = worker;
            Activator           = activator;
            Log                 = log;
            CustomEndpoints     = customEndpoints.ToArray();
            Environment         = environment;
            ExceptionSerializer = exceptionSerializer;
            LoadSheddingConfig  = loadSheddingConfig;
            AppInfo             = appInfo;

            if (serviceEndPointDefinition.UseSecureChannel)
            {
                ServerRootCertHash = certificateLocator.GetCertificate("Service").GetHashOfRootCertificate();
            }

            var urlPrefixTemplate = ServiceEndPointDefinition.UseSecureChannel ? "https://+:{0}/" : "http://+:{0}/";

            Prefix = string.Format(urlPrefixTemplate, ServiceEndPointDefinition.HttpPort);

            Listener = new HttpListener
            {
                IgnoreWriteExceptions = true,
                Prefixes = { Prefix }
            };

            var context = Metric.Context("Service").Context(AppInfo.Name);

            _serializationTime          = context.Timer("Serialization", Unit.Calls);
            _deserializationTime        = context.Timer("Deserialization", Unit.Calls);
            _roundtripTime              = context.Timer("Roundtrip", Unit.Calls);
            _metaEndpointsRoundtripTime = context.Timer("MetaRoundtrip", Unit.Calls);
            _successCounter             = context.Counter("Success", Unit.Calls);
            _failureCounter             = context.Counter("Failed", Unit.Calls);
            _activeRequestsCounter      = context.Timer("ActiveRequests", Unit.Requests);
            _endpointContext            = context.Context("Endpoints");
        }
Example #11
0
 public void Accept(MetricsContext context)
 {
     try
     {
         var serializedMetrics = context.Serialize();
         foreach (var metric in serializedMetrics)
         {
             Console.WriteLine(metric);
         }
     }
     catch (Exception e)
     {
         _logger.LogError("Failed to serialize a MetricsContext: {}", e);
     }
 }
Example #12
0
        /// <summary>
        /// Flushes the current context state to the configured sink.
        /// </summary>
        public void Flush()
        {
            _logger.LogDebug($"Configuring context for environment {_environment.Name}");
            ConfigureContextForEnvironment(_context);
            if (_environment.Sink == null)
            {
                var message = $"No Sink is configured for environment `{_environment.GetType().Name}`";
                throw new InvalidOperationException(message);
            }

            _logger.LogDebug("Sending data to sink. {}", _environment.Sink.GetType().Name);

            _environment.Sink.Accept(_context);
            _context = _context.CreateCopyWithContext();
        }
Example #13
0
 public MetricsLogger(IEnvironment environment, MetricsContext metricsContext, ILoggerFactory loggerFactory)
 {
     if (environment == null)
     {
         throw new ArgumentNullException(nameof(environment));
     }
     if (metricsContext == null)
     {
         throw new ArgumentNullException(nameof(metricsContext));
     }
     _environment = environment;
     _context     = metricsContext;
     _logger      = loggerFactory.CreateLogger <MetricsLogger>();
     _logger.LogDebug($"Resolved environment {_environment.Name} with sink {_environment.Sink.ToString()}");
 }
        public bool AttachContext(string contextName, MetricsContext context)
        {
            if (this.isDisabled)
            {
                return(true);
            }

            if (string.IsNullOrEmpty(contextName))
            {
                throw new ArgumentException("Context name can't be null or empty for attached contexts");
            }
            var attached = this.childContexts.GetOrAdd(contextName, context);

            return(object.ReferenceEquals(attached, context));
        }
Example #15
0
        public MetricsConfig(MetricsContext context)
        {
            this.context = context;

            if (!globalyDisabled)
            {
                this.healthStatus = () => HealthChecks.GetStatus();
                this.reports      = new MetricsReports(this.context.DataProvider, this.healthStatus);
                this.context.Advanced.ContextDisabled += (s, e) =>
                {
                    this.isDisabled |= true;
                    this.DisableAllReports();
                };
            }
        }
Example #16
0
        public TaskIndexRecord AddTask([NotNull] Task task)
        {
            var metricsContextForTaskName = MetricsContext.For(task.Meta);

            if (task.Meta.Attempts == 0)
            {
                rtqProfiler.ProcessTaskCreation(task.Meta);
                metricsContextForTaskName.Meter("TasksQueued").Mark();
            }
            using (metricsContextForTaskName.Timer("CreationTime").NewContext())
            {
                task.Meta.TaskDataId = taskDataStorage.Write(task.Meta, task.Data);
                return(handleTasksMetaStorage.AddMeta(task.Meta, oldTaskIndexRecord: null));
            }
        }
        public static void RegisterCLRAppCounters(MetricsContext context)
        {
            var app = Process.GetCurrentProcess().ProcessName;

            context.Register("Mb in all Heaps", () => new DerivedGauge(new PerformanceCounterGauge(Memory, "# Bytes in all Heaps", app), v => v / (1024 * 1024)), Unit.Custom("Mb"));
            context.Register("Time in GC", () => new PerformanceCounterGauge(Memory, "% Time in GC", app), Unit.Custom("%"));
            context.Register("Total Exceptions", () => new PerformanceCounterGauge(Exceptions, "# of Exceps Thrown", app), Unit.Custom("Exceptions"));
            context.Register("Exceptions Thrown / Sec", () => new PerformanceCounterGauge(Exceptions, "# of Exceps Thrown / Sec", app), Unit.Custom("Exceptions/s"));
            context.Register("Logical Threads", () => new PerformanceCounterGauge(LocksAndThreads, "# of current logical Threads", app), Unit.Custom("Threads"));
            context.Register("Physical Threads", () => new PerformanceCounterGauge(LocksAndThreads, "# of current physical Threads", app), Unit.Custom("Threads"));
            context.Register("Contention Rate / Sec", () => new PerformanceCounterGauge(LocksAndThreads, "Contention Rate / Sec", app), Unit.Custom("Attempts/s"));
            context.Register("Queue Length / sec", () => new PerformanceCounterGauge(LocksAndThreads, "Queue Length / sec", app), Unit.Custom("Threads/s"));

            ThreadPoolMetrics.RegisterThreadPoolGauges(context);
        }
        public void TestAccept()
        {
            String prop          = "TestProp";
            String propValue     = "TestPropValue";
            String logGroupName  = "TestLogGroup";
            String logStreamName = "TestLogStream";

            MetricsContext mc = new MetricsContext();

            mc.PutProperty(prop, propValue);
            mc.PutMetric("Time", 10);

            AgentSink sink = new AgentSink(logGroupName, logStreamName, Endpoint.DEFAULT_TCP_ENDPOINT, _socketClientFactory, _config);

            sink.Accept(mc);
        }
Example #19
0
        public UnitTest()
        {
            var config = Config.GetIConfiguration(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            var setup  = new Setup();

            context = new MetricsContext(setup.Options);
            var mockFactory = new Mock <IHttpClientFactory>();
            var client      = new HttpClient
            {
                BaseAddress = new Uri(config.GetValue <string>("DEVTOURL"))
            };

            mockFactory.Setup(_ => _.CreateClient(It.IsAny <string>())).Returns(client);
            BlogService   = new BlogService(mockFactory.Object, config);
            MetricService = new MetricService(context);
        }
Example #20
0
        public SolutionPort(string solutionFilePath, ILogger logger = null)
        {
            if (logger != null)
            {
                LogHelper.Logger = logger;
            }

            _portSolutionResult        = new PortSolutionResult(solutionFilePath);
            _solutionPath              = solutionFilePath;
            _context                   = new MetricsContext(solutionFilePath);
            _solutionAnalysisResult    = new SolutionResult();
            _solutionRunResult         = new SolutionResult();
            SkipDownloadFiles          = new ConcurrentDictionary <string, bool>();
            _projectTypeFeatureResults = new Dictionary <string, FeatureDetectionResult>();
            CheckCache();
        }
Example #21
0
        public static void RegisterThreadPoolGauges(MetricsContext context)
        {
            context.Gauge("Thread Pool Available Threads", () => { int threads, ports; ThreadPool.GetAvailableThreads(out threads, out ports); return(threads); }, Unit.Threads);
            context.Gauge("Thread Pool Available Completion Ports", () => { int threads, ports; ThreadPool.GetAvailableThreads(out threads, out ports); return(ports); }, Unit.Custom("Ports"));

            context.Gauge("Thread Pool Min Threads", () => { int threads, ports; ThreadPool.GetMinThreads(out threads, out ports); return(threads); }, Unit.Threads);
            context.Gauge("Thread Pool Min Completion Ports", () => { int threads, ports; ThreadPool.GetMinThreads(out threads, out ports); return(ports); }, Unit.Custom("Ports"));

            context.Gauge("Thread Pool Max Threads", () => { int threads, ports; ThreadPool.GetMaxThreads(out threads, out ports); return(threads); }, Unit.Threads);
            context.Gauge("Thread Pool Max Completion Ports", () => { int threads, ports; ThreadPool.GetMaxThreads(out threads, out ports); return(ports); }, Unit.Custom("Ports"));

            var currentProcess = Process.GetCurrentProcess();

            context.Gauge(currentProcess.ProcessName + " Uptime", () => (DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime()).TotalSeconds, Unit.Custom("Seconds"));
            context.Gauge(currentProcess.ProcessName + " Threads", () => Process.GetCurrentProcess().Threads.Count, Unit.Threads);
        }
        internal static void RegisterThreadPoolGauges(MetricsContext context)
        {
            context.Gauge("Thread Pool Available Threads", () => { int threads, ports; ThreadPool.GetAvailableThreads(out threads, out ports); return threads; }, Unit.Threads, tags: "threads");
            context.Gauge("Thread Pool Available Completion Ports", () => { int threads, ports; ThreadPool.GetAvailableThreads(out threads, out ports); return ports; }, Unit.Custom("Ports"), tags: "threads");

            context.Gauge("Thread Pool Min Threads", () => { int threads, ports; ThreadPool.GetMinThreads(out threads, out ports); return threads; }, Unit.Threads, tags: "threads");
            context.Gauge("Thread Pool Min Completion Ports", () => { int threads, ports; ThreadPool.GetMinThreads(out threads, out ports); return ports; }, Unit.Custom("Ports"), tags: "threads");

            context.Gauge("Thread Pool Max Threads", () => { int threads, ports; ThreadPool.GetMaxThreads(out threads, out ports); return threads; }, Unit.Threads, tags: "threads");
            context.Gauge("Thread Pool Max Completion Ports", () => { int threads, ports; ThreadPool.GetMaxThreads(out threads, out ports); return ports; }, Unit.Custom("Ports"), tags: "threads");

            var currentProcess = Process.GetCurrentProcess();
            Func<TimeSpan> uptime = () => (DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime());
            context.Gauge(currentProcess.ProcessName + " Uptime Seconds", () => uptime().TotalSeconds, Unit.Custom("Seconds"));
            context.Gauge(currentProcess.ProcessName + " Uptime Hours", () => uptime().TotalHours, Unit.Custom("Hours"));
            context.Gauge(currentProcess.ProcessName + " Threads", () => Process.GetCurrentProcess().Threads.Count, Unit.Threads, tags: "threads");
        }
Example #23
0
        public AsyncCache(ILog log, MetricsContext metrics, IDateTime dateTime)
        {
            DateTime = dateTime;
            Log      = log;

            if (ObjectCache.Host == null)
            {
                ObjectCache.Host = this;
            }
            else
            {
                Log.Error("AsyncCache: Failed to register with ObjectCache.Host since it was already registered. Cache memory size will not be reported to Metrics.NET. Please make sure AsyncCache is singleton to prevent this issue.");
            }

            Clear();

            Metrics = metrics;
            InitMetrics();
        }
        public void TestOverrideDefaultDimensions()
        {
            var dimensionName   = "dim";
            var dimensionValue  = "dimValue";
            var defaultDimName  = "defaultDim";
            var defaultDimValue = "defaultDimValue";

            MetricsContext metricsContext = new MetricsContext();

            metricsContext.DefaultDimensions.AddDimension(defaultDimName, defaultDimValue);
            metricsContext.SetDimensions(new DimensionSet(defaultDimName, defaultDimValue));

            _metricsLogger = new MetricsLogger(_environment, metricsContext, _logger);
            _metricsLogger.SetDimensions(new DimensionSet(dimensionName, dimensionValue));
            _metricsLogger.Flush();

            Assert.Single(_sink.MetricsContext.GetAllDimensionSets());
            Assert.Null(_sink.MetricsContext.GetAllDimensionSets()[0].GetDimensionValue(defaultDimName));
        }
 /// <summary>
 /// Since this object is a registered updater, this method will be called
 /// periodically, e.g.
 /// </summary>
 /// <remarks>
 /// Since this object is a registered updater, this method will be called
 /// periodically, e.g. every 5 seconds.
 /// </remarks>
 public virtual void DoUpdates(MetricsContext unused)
 {
     lock (this)
     {
         metricsRecord.IncrMetric("maps_launched", numMapTasksLaunched);
         metricsRecord.IncrMetric("maps_completed", numMapTasksCompleted);
         metricsRecord.IncrMetric("reduces_launched", numReduceTasksLaunched);
         metricsRecord.IncrMetric("reduces_completed", numReduceTasksCompleted);
         metricsRecord.IncrMetric("waiting_maps", numWaitingMaps);
         metricsRecord.IncrMetric("waiting_reduces", numWaitingReduces);
         numMapTasksLaunched     = 0;
         numMapTasksCompleted    = 0;
         numReduceTasksLaunched  = 0;
         numReduceTasksCompleted = 0;
         numWaitingMaps          = 0;
         numWaitingReduces       = 0;
     }
     metricsRecord.Update();
 }
Example #26
0
        /// <summary>
        /// Initializes a new instance of Solution Port, analyzing the solution path using the provided config.
        /// WARNING: This constructor will rebuild and reanalyze the solution, which will have a performance impact. If you
        /// have an already analyzed solution, use another constructor
        /// </summary>
        /// <param name="solutionFilePath">Path to solution file</param>
        /// <param name="solutionConfiguration">Configuration for each project in solution to be built</param>
        public SolutionPort(string solutionFilePath, List <PortCoreConfiguration> solutionConfiguration, ILogger logger = null)
        {
            if (logger != null)
            {
                LogHelper.Logger = logger;
            }
            _portSolutionResult = new PortSolutionResult(solutionFilePath);
            SkipDownloadFiles   = new ConcurrentDictionary <string, bool>();
            _solutionPath       = solutionFilePath;
            AnalyzerConfiguration analyzerConfiguration = new AnalyzerConfiguration(LanguageOptions.CSharp)
            {
                MetaDataSettings = new MetaDataSettings()
                {
                    Annotations           = true,
                    DeclarationNodes      = true,
                    MethodInvocations     = true,
                    ReferenceData         = true,
                    LoadBuildData         = true,
                    InterfaceDeclarations = true,
                    MemberAccess          = true,
                    ElementAccess         = true
                }
            };

            CodeAnalyzer analyzer = CodeAnalyzerFactory.GetAnalyzer(analyzerConfiguration, LogHelper.Logger);

            List <AnalyzerResult> analyzerResults = null;

            //We are building using references
            if (solutionConfiguration.Any(p => p.MetaReferences?.Any() == true))
            {
                var currentReferences   = solutionConfiguration.ToDictionary(s => s.ProjectPath, s => s.MetaReferences);
                var frameworkReferences = solutionConfiguration.ToDictionary(s => s.ProjectPath, s => s.FrameworkMetaReferences);
                analyzerResults = analyzer.AnalyzeSolution(solutionFilePath, frameworkReferences, currentReferences).Result;
            }
            else
            {
                analyzerResults = analyzer.AnalyzeSolution(solutionFilePath).Result;
            }

            _context = new MetricsContext(solutionFilePath, analyzerResults);
            InitSolutionRewriter(analyzerResults, solutionConfiguration);
        }
Example #27
0
        static void AddComputerUsageData(Object o)
        {
            var fullDataManager = new FullDataManager();
            var computersummary = fullDataManager.GetComputerSummary();

            using (var _ctx = new MetricsContext())
            {
                var metrics = _ctx.ComputerMetrics.FirstOrDefault(p => p.Name == computersummary.Name);
                metrics.UsageDatas.Add(new UsageData()
                {
                    AvailableDiskSpaceGb   = computersummary.AvailableDiskSpaceGb,
                    AverageDiskQueueLength = computersummary.AverageDiskQueueLength,
                    CpuUsage = computersummary.CpuUsage,
                    RamUsage = computersummary.RamUsage,
                    Time     = DateTime.Now,
                });
                _ctx.SaveChanges();
            }
        }
        public ServiceProxyProvider(string serviceName, IEventPublisher <ClientCallEvent> eventPublisher,
                                    ILog log,
                                    Func <string, ReachabilityCheck, IMultiEnvironmentServiceDiscovery> serviceDiscoveryFactory,
                                    Func <DiscoveryConfig> getConfig,
                                    JsonExceptionSerializer exceptionSerializer,
                                    CurrentApplicationInfo appInfo,
                                    Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory,
                                    IMicrodotTypePolicySerializationBinder serializationBinder)
        {
            JsonSettings.SerializationBinder = serializationBinder;

            EventPublisher = eventPublisher;

            Log = log;

            ServiceName         = serviceName;
            GetDiscoveryConfig  = getConfig;
            ExceptionSerializer = exceptionSerializer;
            AppInfo             = appInfo;

            var metricsContext = Metric.Context(METRICS_CONTEXT_NAME).Context(ServiceName);

            _serializationTime   = metricsContext.Timer("Serialization", Unit.Calls);
            _deserializationTime = metricsContext.Timer("Deserialization", Unit.Calls);
            _roundtripTime       = metricsContext.Timer("Roundtrip", Unit.Calls);

            _successCounter              = metricsContext.Counter("Success", Unit.Calls);
            _failureCounter              = metricsContext.Counter("Failed", Unit.Calls);
            _hostFailureCounter          = metricsContext.Counter("HostFailure", Unit.Calls);
            _applicationExceptionCounter = metricsContext.Counter("ApplicationException", Unit.Calls);

            _httpMessageHandlerFactory = messageHandlerFactory;

            ServiceDiscovery = serviceDiscoveryFactory(serviceName, ValidateReachability);

            var globalConfig  = GetDiscoveryConfig();
            var serviceConfig = GetConfig();

            _httpsTestInterval = TimeSpan.FromMinutes(serviceConfig.TryHttpsIntervalInMinutes ?? globalConfig.TryHttpsIntervalInMinutes);

            _connectionContext = Metric.Context("Connections");
        }
Example #29
0
        public void Setup()
        {
            SolutionPath = "temp/solutionPath";
            ProjectPath  = "temp/solutionPath";

            var projectResult = new ProjectWorkspace(ProjectPath)
            {
                ProjectGuid = "1234-5678"
            };
            var analyzerResult = new AnalyzerResult
            {
                ProjectResult = projectResult
            };
            var analyzerResults = new List <AnalyzerResult>
            {
                analyzerResult
            };

            Context = new MetricsContext(SolutionPath, analyzerResults);
        }
Example #30
0
 private static void Register(this MetricsContext context, string name, Unit unit,
                              string category, string counter, string instance = null,
                              Func <double, double> derivate = null,
                              MetricTags tags = default(MetricTags))
 {
     try
     {
         WrappedRegister(context, name, unit, category, counter, instance, derivate, tags);
     }
     catch (UnauthorizedAccessException x)
     {
         var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() +
                       ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group.";
         MetricsErrorHandler.Handle(x, message);
     }
     catch (Exception x)
     {
         var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() +
                       ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group.";
         MetricsErrorHandler.Handle(x, message);
     }
 }
Example #31
0
        public AsyncCache(ILog log, MetricsContext metrics, IDateTime dateTime, IRevokeListener revokeListener)
        {
            DateTime = dateTime;
            Log      = log;

            if (ObjectCache.Host == null)
            {
                ObjectCache.Host = this;
            }
            else
            {
                Log.Error("AsyncCache: Failed to register with ObjectCache.Host since it was already registered. Cache memory size will not be reported to Metrics.NET. Please make sure AsyncCache is singleton to prevent this issue.");
            }

            Clear();

            Metrics = metrics;
            InitMetrics();
            var onRevoke = new ActionBlock <string>(OnRevoke);

            RevokeDisposable = revokeListener.RevokeSource.LinkTo(onRevoke);
        }
Example #32
0
        static void AddComputerMetrics()
        {
            var fullDataManager = new FullDataManager();
            var computersummary = fullDataManager.GetComputerSummary();

            using (var _ctx = new MetricsContext())
            {
                var metrics = _ctx.ComputerMetrics.FirstOrDefault(p => p.Name == computersummary.Name);
                if (metrics == null)
                {
                    metrics           = _ctx.ComputerMetrics.Create();
                    metrics.Cpu       = computersummary.Cpu;
                    metrics.Ip        = computersummary.Ip.ToString();
                    metrics.Name      = computersummary.Name;
                    metrics.Ram       = computersummary.Ram;
                    metrics.User      = computersummary.User;
                    metrics.VideoCard = computersummary.VideoCard;
                    _ctx.ComputerMetrics.Add(metrics);
                    _ctx.SaveChanges();
                }
            }
        }
        internal static void RegisterAppCounters(MetricsContext context)
        {
            var app = Process.GetCurrentProcess().ProcessName;

            context.Register("Process CPU Usage", Unit.Percent, "Process", "% Processor Time", app, derivate: v => v / Environment.ProcessorCount, tags: "cpu");
            context.Register("Process User Time", Unit.Percent, "Process", "% User Time", app, derivate: v => v / Environment.ProcessorCount, tags: "cpu");
            context.Register("Process Privileged Time", Unit.Percent, "Process", "% Privileged Time", app, derivate: v => v / Environment.ProcessorCount, tags: "cpu");

            context.Register("Private MBytes", Unit.MegaBytes, "Process", "Private Bytes", app, derivate: v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Working Set", Unit.MegaBytes, "Process", "Working Set", app, derivate: v => v / (1024 * 1024.0), tags: "memory");

            context.Register("Mb in all Heaps", Unit.MegaBytes, Memory, "# Bytes in all Heaps", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Gen 0 heap size", Unit.MegaBytes, Memory, "Gen 0 heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Gen 1 heap size", Unit.MegaBytes, Memory, "Gen 1 heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Gen 2 heap size", Unit.MegaBytes, Memory, "Gen 2 heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Large Object Heap size", Unit.MegaBytes, Memory, "Large Object Heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Allocated Bytes/second", Unit.KiloBytes, Memory, "Allocated Bytes/sec", app, v => v / 1024.0, tags: "memory");

            context.Register("Time in GC", Unit.Custom("%"), Memory, "% Time in GC", app, tags: "memory");
            context.Register("Pinned Objects", Unit.Custom("Objects"), Memory, "# of Pinned Objects", app, tags: "memory");

            context.Register("Total Exceptions", Unit.Custom("Exceptions"), Exceptions, "# of Exceps Thrown", app, tags: "exceptions");
            context.Register("Exceptions Thrown / Sec", Unit.Custom("Exceptions"), Exceptions, "# of Exceps Thrown / Sec", app, tags: "exceptions");
            context.Register("Except Filters / Sec", Unit.Custom("Filters"), Exceptions, "# of Filters / Sec", app, tags: "exceptions");
            context.Register("Finallys / Sec", Unit.Custom("Finallys"), Exceptions, "# of Finallys / Sec", app, tags: "exceptions");
            context.Register("Throw to Catch Depth / Sec", Unit.Custom("Stack Frames"), Exceptions, "Throw to Catch Depth / Sec", app, tags: "exceptions");

            context.Register("Logical Threads", Unit.Threads, LocksAndThreads, "# of current logical Threads", app, tags: "threads");
            context.Register("Physical Threads", Unit.Threads, LocksAndThreads, "# of current physical Threads", app, tags: "threads");
            context.Register("Contention Rate / Sec", Unit.Custom("Attempts"), LocksAndThreads, "Contention Rate / Sec", app, tags: "threads");
            context.Register("Total Contentions", Unit.Custom("Attempts"), LocksAndThreads, "Total # of Contentions", app, tags: "threads");
            context.Register("Queue Length / sec", Unit.Threads, LocksAndThreads, "Queue Length / sec", app, tags: "threads");

            context.Register("IO Data Operations/sec", Unit.Custom("IOPS"), "Process", "IO Data Operations/sec", app, tags: "disk");
            context.Register("IO Other Operations/sec", Unit.Custom("IOPS"), "Process", "IO Other Operations/sec", app, tags: "disk");

            ThreadPoolMetrics.RegisterThreadPoolGauges(context);
        }
 public ErrorMeterMiddleware(MetricsContext context, string metricName, Regex[] ignorePatterns)
     : base(ignorePatterns)
 {
     this.errorMeter = context.Meter(metricName, Unit.Errors);
 }
 public NancyMetricsConfig(MetricsContext metricsContext, Func<HealthStatus> healthStatus, IPipelines nancyPipelines)
 {
     this.metricsContext = metricsContext;
     this.healthStatus = healthStatus;
     this.nancyPipelines = nancyPipelines;
 }
 public NancyGlobalMetrics(MetricsContext context, IPipelines nancyPipelines)
 {
     this.nancyPipelines = nancyPipelines;
     this.context = context;
     nancyGlobalMetricsContext = context;
 }
 public OwinRequestMetricsConfig(Action<object> middlewareRegistration, MetricsContext metricsContext, Regex[] ignoreRequestPathPatterns)
 {
     this.middlewareRegistration = middlewareRegistration;
     this.metricsContext = metricsContext;
     this.ignoreRequestPathPatterns = ignoreRequestPathPatterns;
 }
 public TimerForEachRequestMiddleware(MetricsContext context, Regex[] ignorePatterns)
     : base(ignorePatterns)
 {
     this.context = context;
 }
 public ActiveRequestCounterMiddleware(MetricsContext context, string metricName, Regex[] ignorePatterns)
     : base(ignorePatterns)
 {
     this.activeRequests = context.Counter(metricName, Unit.Custom("ActiveRequests"));
 }
Example #40
0
 public OwinMetricsConfig(Action<object> middlewareRegistration, MetricsContext context, Func<HealthStatus> healthStatus)
 {
     this.middlewareRegistration = middlewareRegistration;
     this.context = context;
     this.healthStatus = healthStatus;
 }
 public RequestTimerMiddleware(MetricsContext context, string metricName, Regex[] ignorePatterns)
     : base(ignorePatterns)
 {
     this.requestTimer = context.Timer(metricName, Unit.Requests);
 }
 public PostAndPutRequestSizeHistogramMiddleware(MetricsContext context, string metricName, Regex[] ignorePatterns)
     : base(ignorePatterns)
 {
     this.histogram = context.Histogram(metricName, Unit.Bytes, SamplingType.FavourRecent);
 }
        private static void WrappedRegister(MetricsContext context, string name, Unit unit,
            string category, string counter, string instance = null,
            Func<double, double> derivate = null,
            MetricTags tags = default(MetricTags))
        {
            log.Debug(() => string.Format("Registering performance counter [{0}] in category [{1}] for instance [{2}]", counter, category, instance ?? "none"));

            if (PerformanceCounterCategory.Exists(category))
            {
                if (instance == null || PerformanceCounterCategory.InstanceExists(instance, category))
                {
                    if (PerformanceCounterCategory.CounterExists(counter, category))
                    {
                        var counterTags = new MetricTags(tags.Tags.Concat(new[] { "PerfCounter" }));
                        if (derivate == null)
                        {
                            context.Advanced.Gauge(name, () => new PerformanceCounterGauge(category, counter, instance), unit, counterTags);
                        }
                        else
                        {
                            context.Advanced.Gauge(name, () => new DerivedGauge(new PerformanceCounterGauge(category, counter, instance), derivate), unit, counterTags);
                        }
                        return;
                    }
                }
            }

            log.ErrorFormat("Performance counter does not exist [{0}] in category [{1}] for instance [{2}]", counter, category, instance ?? "none");
        }