public static void GetDogfoodCPUSeries() { var testCertificateThumbprint = "C35CBFF9FA6C51E51E1DE97B6D1E246F27661301"; var httpsUrl = "https://shoebox2.metrics.nsatc.net/public/monitoringAccount/SignalRShoeboxTest/homeStamp"; var connectionInfo = new ConnectionInfo(new Uri(httpsUrl), testCertificateThumbprint, StoreLocation.LocalMachine); var reader = new MetricReader(connectionInfo); // Single metric var id = new MetricIdentifier("SignalRShoeboxTest", "systemLoad", "PodCpuUsage"); //var id = new MetricIdentifier("SignalRShoeboxTest", "ShoeboxInternal", "MessageCountRaw"); //var id = new MetricIdentifier("SignalRShoeboxTest", "systemLoad", "PodMemory"); // The short link for this series is http://jarvis-int.dc.ad.msft.net/D10A9E2E. var definition = new TimeSeriesDefinition <MetricIdentifier>( id, new Dictionary <string, string> { //{ "ResourceId", resourceId} { "resourceKubeId", "62a558c2-2895-423d-a7b0-05b03a15b65a" } }); TimeSeries <MetricIdentifier, double?> result = reader.GetTimeSeriesAsync(DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow, SamplingType.Max, definition).Result; foreach (var dataPoint in result.Datapoints) { Console.WriteLine("Time: {0}, Value: {1}", dataPoint.TimestampUtc, dataPoint.Value); } Console.WriteLine(JsonConvert.SerializeObject(result)); Console.WriteLine("############################ END OF GetDogfoodSeries ##############################"); }
/// <summary> /// Gets the monitors for the given <paramref name="metricIdentifier"/>. /// </summary> /// <param name="metricIdentifier">The metric identifier.</param> /// <returns>The monitors for the given <paramref name="metricIdentifier"/>.</returns> public async Task <IReadOnlyList <MonitorIdentifier> > GetMonitorsAsync(MetricIdentifier metricIdentifier) { metricIdentifier.Validate(); string url = string.Format( "{0}{1}/monitoringAccount/{2}/metricNamespace/{3}/metric/{4}/monitorIDs", this.connectionInfo.GetEndpoint(metricIdentifier.MonitoringAccount), this.ConfigRelativeUrlV2, metricIdentifier.MonitoringAccount, SpecialCharsHelper.EscapeTwice(metricIdentifier.MetricNamespace), SpecialCharsHelper.EscapeTwice(metricIdentifier.MetricName)); var response = await this.GetResponseAsStringDelegate( new Uri(url), HttpMethod.Get, this.httpClient, metricIdentifier.MonitoringAccount, this.ConfigRelativeUrlV2, null, string.Empty, null, null, MetricQueryResponseDeserializer.CurrentVersion, NumAttempts).ConfigureAwait(false); return(JsonConvert.DeserializeObject <MonitorIdentifier[]>(response.Item1)); }
public static void UnregisterHealthCheck(string healthCheckName, MetricTags tags = default(MetricTags)) { HealthCheck healthCheck; var name = MetricIdentifier.Calculate(healthCheckName, tags); checks.TryRemove(name, out healthCheck); }
private Metric GetAppInsightsMetric(MetricIdentifier id, params string[] dimensionNames) { if (dimensionNames == null) { return(_telemetryClient.GetMetric(id)); } switch (dimensionNames.Length) { case 1: return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0])); case 2: return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0], dimensionNames[1])); case 3: return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0], dimensionNames[1], dimensionNames[2])); case 4: return(_telemetryClient.GetMetric(id.MetricId, dimensionNames[0], dimensionNames[1], dimensionNames[2], dimensionNames[3])); default: throw new Exception("Too many dimensions"); } }
public void WriteMetric(string name, double value, params KeyValuePair <string, string>[] dimensions) { if (_settings.UsePrometheus) { if (!_prometheusMetrics.TryGetValue(name, out var counter)) { counter = Metrics.CreateCounter(name, name, dimensions?.Select(p => p.Key).ToArray()); _prometheusMetrics.AddOrUpdate(name, counter, (k, v) => counter); } counter.Inc(value); } if (_settings.UseAppInsights && _telemetryClient != null) { var id = new MetricIdentifier(_settings.AppInsights.Namespace, name); if (!_aiMetrics.TryGetValue(id.MetricId, out var metric)) { metric = GetAppInsightsMetric(id, dimensions?.Select(p => p.Key).ToArray()); _aiMetrics.AddOrUpdate(id.MetricId, metric, (k, v) => metric); } TrackValue(metric, value, dimensions?.Select(p => p.Value).ToArray()); } }
/// <summary> /// Initializes a new instance of the <see cref="FilteredTimeSeriesQueryRequest" /> class. /// </summary> /// <param name="metricIdentifier">The metric identifier.</param> /// <param name="samplingTypes">The sampling types.</param> /// <param name="dimensionFilters">The dimension filters.</param> /// <param name="startTimeUtc">The start time UTC.</param> /// <param name="endTimeUtc">The end time UTC.</param> /// <param name="seriesResolutionInMinutes">The series resolution in minutes.</param> /// <param name="aggregationType">Type of the aggregation.</param> /// <param name="topPropertyDefinition">The top property definition.</param> /// <param name="numberOfResultsToReturn">The number of results to return.</param> /// <param name="orderBy">The order by.</param> /// <param name="zeroAsNoValueSentinel">Indicates whether zero should be used as no value sentinel, or double.NaN.</param> /// <param name="outputDimensionNames">The dimension names to be used for the result time series. If not set, same as the dimensions in the dimension filter.</param> /// <param name="lastValueMode">Indicating if the query should be fulfilled with last value mode. If true, null values in the query range requested will be filled with the last known value.</param> public FilteredTimeSeriesQueryRequest( MetricIdentifier metricIdentifier, IReadOnlyList <SamplingType> samplingTypes, IReadOnlyList <DimensionFilter> dimensionFilters, DateTime startTimeUtc, DateTime endTimeUtc, int seriesResolutionInMinutes, AggregationType aggregationType, PropertyDefinition topPropertyDefinition, int numberOfResultsToReturn, OrderBy orderBy, bool zeroAsNoValueSentinel, IReadOnlyList <string> outputDimensionNames = null, bool lastValueMode = false) : this( metricIdentifier, null, null, null, samplingTypes, dimensionFilters, startTimeUtc, endTimeUtc, seriesResolutionInMinutes, aggregationType, topPropertyDefinition, numberOfResultsToReturn, orderBy, zeroAsNoValueSentinel, false, outputDimensionNames, lastValueMode) { }
/// <summary> /// Update the number of EventDetail items reported by the report. /// </summary> /// <param name="reportIdentifier">The unique identifier for a report.</param> /// <param name="events">The events reported by the reporter.</param> public static void UpdateTotalReportedEvents(int reportIdentifier, IEnumerable <EventValueSource> events) { if (reportIdentifier >= 0 && reportIdentifier < ReportEventCounts.Count) { foreach (var evntSrc in events) { var count = evntSrc.Value.Events.Count; var eventMetricId = MetricIdentifier.Calculate(evntSrc.Name, evntSrc.Tags); var report = ReportEventCounts[reportIdentifier]; var eventCount = report.FirstOrDefault(e => e.EventMetricIdentifier == eventMetricId); if (eventCount != null) { eventCount.TotalEventsReported = count; } else { report.Add(new EventCount { EventMetricIdentifier = eventMetricId, TotalEventsReported = count }); } } } }
public MonitorIdentifier(MetricIdentifier metricIdentifier, string monitorId) { if (monitorId == null) { throw new ArgumentNullException("monitorId"); } this.metricIdentifier = metricIdentifier; this.monitorId = monitorId; }
public AppInsightsHeartbeat( TelemetryClient telemetryClient, ILogger <AppInsightsHeartbeat> logger, IOptions <AppInsightsSettings> settings) { _logger = logger; var metricId = new MetricIdentifier(settings.Value.Namespace, $"{settings.Value.Role}.heartbeat"); _heartbeat = telemetryClient.GetMetric(metricId); }
/// <summary> /// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br /> /// Optionally specify a metric configuration to control how the tracked values are aggregated. /// </summary> /// <param name="telemetryClient">The aggregated values will be sent to the <c>TelemetryConfiguration</c> /// associated with this client.<br /> /// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this /// means that all values tracked for a given metric ID and dimensions will be aggregated together /// across all clients that share the same <c>TelemetryConfiguration</c>.</param> /// <param name="metricIdentifier">A grouping containing the Namespace, the ID (name) and the dimension names of the metric.</param> /// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions /// and aggregation scope, but with a different configuration. When calling this method to get a previously /// created metric, you can simply avoid specifying any configuration (or specify null) to imply the /// configuration used earlier.</exception> /// <returns></returns> public static Metric GetMetric( this TelemetryClient telemetryClient, MetricIdentifier metricIdentifier) { return(GetOrCreateMetric( telemetryClient, MetricAggregationScope.TelemetryConfiguration, metricIdentifier, metricConfiguration: null)); }
/// <summary> /// Initializes a new instance of the <see cref="FilteredTimeSeries" /> class. /// Create a single time series. /// </summary> /// <param name="metricIdentifier">The metric identifier.</param> /// <param name="dimensionList">The list of dimensions.</param> /// <param name="evaluatedResult">The evaluated result.</param> /// <param name="seriesValues">The time series values, only included if specified in the query.</param> internal FilteredTimeSeries( MetricIdentifier metricIdentifier, IReadOnlyList <KeyValuePair <string, string> > dimensionList, double evaluatedResult, IReadOnlyList <KeyValuePair <SamplingType, double[]> > seriesValues) { this.MetricIdentifier = metricIdentifier; this.DimensionList = dimensionList; this.EvaluatedResult = evaluatedResult; this.TimeSeriesValues = seriesValues; }
/// <summary> /// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br /> /// Optionally specify a metric configuration to control how the tracked values are aggregated. /// </summary> /// <param name="telemetryClient">The aggregated values will be sent using the specified client.</param> /// <param name="metricIdentifier">A grouping containing the Namespace, the ID (name) and the dimension names of the metric.</param> /// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br /> /// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param> /// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times /// with the same metric ID and dimensions for a given aggregation scope, you will receive the same /// instance of <c>Metric</c>.</returns> /// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions /// and aggregation scope, but with a different configuration. When calling this method to get a previously /// created metric, you can simply avoid specifying any configuration (or specify null) to imply the /// configuration used earlier.</exception> /// <param name="aggregationScope">The scope across which the values for the metric are to be aggregated in memory. /// See <see cref="MetricAggregationScope" /> for more info.</param> public static Metric GetMetric( this TelemetryClient telemetryClient, MetricIdentifier metricIdentifier, MetricConfiguration metricConfiguration, MetricAggregationScope aggregationScope) { return(GetOrCreateMetric( telemetryClient, aggregationScope, metricIdentifier, metricConfiguration)); }
/// <summary> /// Reads the monitor information. /// </summary> public static void ReadMonitorInfo() { // Replace 31280E2F2D2220808315C212DF8062A295B28325 with your cert thumbprint, // install it to the "Personal\Certificates" folder in the "Local Computer" certificate store, // and grant the permission of reading the private key to the service/application using the MDM consumption APIs. string testCertificateThumbprint = "31280E2F2D2220808315C212DF8062A295B28325"; var connectionInfo = new ConnectionInfo(testCertificateThumbprint, StoreLocation.LocalMachine, MdmEnvironment.Int); var reader = new MonitorReader(connectionInfo); var id = new MetricIdentifier("MetricTeamInternalMetrics", "PlatformMetrics", "\\Memory\\Available MBytes"); IReadOnlyList <MonitorIdentifier> result = reader.GetMonitorsAsync(id).Result; Console.WriteLine("There are {0} monitors under {1} - {2}.\n", result.Count, id.MetricName, JsonConvert.SerializeObject(result)); var allMonitors = reader.GetMonitorsAsync(id.MonitoringAccount).Result; Console.WriteLine("There are {0} monitors under {1} - {2}.\n", allMonitors.Count, id.MonitoringAccount, JsonConvert.SerializeObject(allMonitors)); var definition = new TimeSeriesDefinition <MonitorIdentifier>( result[0], new Dictionary <string, string> { { "Datacenter", "westus" }, { "__Role", "metrics.server" } }); IMonitorHealthStatus result2 = reader.GetCurrentHeathStatusAsync(definition).Result; Console.WriteLine("The current health status is {0}.\n", JsonConvert.SerializeObject(result2)); var definition2 = new TimeSeriesDefinition <MonitorIdentifier>( result[0], new Dictionary <string, string> { { "Datacenter", "eastus2" }, { "__Role", "metrics.server" } }); var statuses = reader.GetMultipleCurrentHeathStatusesAsync(definition, definition2).Result; Console.WriteLine("The current health statuses are: \n{0}.\n{1}.\n ", JsonConvert.SerializeObject(statuses[0]), JsonConvert.SerializeObject(statuses[1])); // The short link for the history is http://jarvis-int.dc.ad.msft.net/44EA28BD TimeSeries <MonitorIdentifier, bool?> result3 = reader.GetMonitorHistoryAsync(DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow, definition).Result; Console.WriteLine("The monitor health history is:"); foreach (var datapoint in result3.Datapoints) { Console.WriteLine("Time: {0}, Result: {1}", datapoint.TimestampUtc, datapoint.Value); } Console.WriteLine("############################ END OF ReadMonitorInfo ##############################"); }
private Metric GetMetric(MetricIdentifier identifier) { lock (_metrics) { if (!_metrics.ContainsKey(identifier)) { var metric = _telemetryClient.GetMetric(identifier.ToString()); _metrics[identifier] = metric; } return(_metrics[identifier]); } }
public void Calculate_WithInvertedTagValueOptions_ReturnsDifferentHashCodes() { var tempTags1 = new Dictionary <string, string>(); tempTags1.Add("key", "value"); var tempTags2 = new Dictionary <string, string>(); tempTags2.Add("value", "key"); var result1 = MetricIdentifier.Calculate("test", tempTags1); var result2 = MetricIdentifier.Calculate("test", tempTags2); result1.Should().NotBe(result2); }
private static Metric GetOrCreateMetric( TelemetryClient telemetryClient, MetricAggregationScope aggregationScope, MetricIdentifier metricIdentifier, MetricConfiguration metricConfiguration) { Util.ValidateNotNull(telemetryClient, nameof(telemetryClient)); MetricManager metricManager = telemetryClient.GetMetricManager(aggregationScope); Metric metric = metricManager.Metrics.GetOrCreate(metricIdentifier, metricConfiguration); return(metric); }
public void Calculate_WithDiffTagKeySameValue_ReturnsDifferentHashCodes() { var tempTags1 = new Dictionary <string, string>(); tempTags1.Add("key1", "abc"); var tempTags2 = new Dictionary <string, string>(); tempTags2.Add("key2", "abc"); var result1 = MetricIdentifier.Calculate("test", tempTags1); var result2 = MetricIdentifier.Calculate("test", tempTags2); result1.Should().NotBe(result2); }
public static bool UploadObject(TelemetryClient tc, object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } List <PropertyInfo> allProperties = null; String name = null; if (obj is Type) { allProperties = (obj as Type).GetProperties().ToList(); name = (obj as Type).Name; } else { allProperties = obj.GetType().GetProperties().ToList(); name = obj.ToString(); } var boolProperties = (from a in allProperties where a.PropertyType == typeof(bool) select a).ToList(); //var propnames = (from a in boolProperties select a.Name).ToList(); MetricIdentifier micount = new MetricIdentifier(name, "MetricsReportCount"); var mcount = tc.GetMetric(micount); mcount.TrackValue(1); foreach (var prop in boolProperties) { MetricIdentifier mi = new MetricIdentifier(name, prop.Name); var metric = tc.GetMetric(mi); var val = prop.GetValue(obj, null); Console.WriteLine("{0}={1}", prop.Name, val); if (Boolean.TryParse(val.ToString(), out bool boolval)) { if (boolval) { metric.TrackValue(1); } else { metric.TrackValue(0); } } } return(true); }
private void InitializeMetrics() { _incomingRequestsDurationMetric = Client.GetMetric(Constants.IncomingRequestsDurationMetricName, Constants.ServiceLineKey, Constants.ServiceNameKey, Constants.ResultCodeKey); _outgoingRequestsDurationMetric = Client.GetMetric(Constants.OutgoingRequestsDurationMetricName, Constants.ServiceLineKey, Constants.ServiceNameKey, Constants.ResultCodeKey); _errorsCountMetric = Client.GetMetric(Constants.ErrorsCountMetricName, Constants.ServiceLineKey, Constants.ServiceNameKey, Constants.ErrorTypeKey); var jobDurationMetricId = new MetricIdentifier(Constants.JobDurationMetricName, Constants.ServiceLineKey, Constants.ServiceNameKey, Constants.ResultCodeKey, Constants.OperationNameKey); _jobDurationMetric = Client.GetMetric(jobDurationMetricId); }
/// <summary> /// Deletes the metric configuration. /// </summary> /// <param name="metricIdentifier">The metric identifier.</param> /// <returns>A task representing the deletion of the configuration.</returns> /// <remarks> /// It deletes only the metric configuration, not the metric data. /// </remarks> public async Task Delete(MetricIdentifier metricIdentifier) { string url = string.Format( "{0}{1}/monitoringAccount/{2}/metricNamespace/{3}/metric/{4}", this.connectionInfo.GetEndpoint(metricIdentifier.MonitoringAccount), this.ConfigRelativeUrl, metricIdentifier.MonitoringAccount, SpecialCharsHelper.EscapeTwice(metricIdentifier.MetricNamespace), SpecialCharsHelper.EscapeTwice(metricIdentifier.MetricName)); await HttpClientHelper.GetResponse( new Uri(url), HttpMethod.Delete, this.httpClient, metricIdentifier.MonitoringAccount, this.ConfigRelativeUrl).ConfigureAwait(false); }
private static SeriesMetadata DeserializeTimeSeriesMetadata(BinaryReader reader, Dictionary <int, string> stringTable) { var metricIdentifier = new MetricIdentifier( DeserializeStringByIndex(reader, stringTable), DeserializeStringByIndex(reader, stringTable), DeserializeStringByIndex(reader, stringTable)); var dimensionsCount = reader.ReadByte(); var dimensionNames = new string[dimensionsCount]; for (var i = 0; i < dimensionsCount; i++) { dimensionNames[i] = DeserializeStringByIndex(reader, stringTable); } return(new SeriesMetadata(metricIdentifier, dimensionNames)); }
public static bool UploadObject(TelemetryClient tc, object obj) { if (tc == null) { throw new ArgumentNullException(nameof(tc)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } PropertyInfo[] allProperties; string name; if (obj is Type objAsType) { allProperties = objAsType.GetProperties(); name = objAsType.Name; } else { allProperties = obj.GetType().GetProperties(); name = obj.ToString(); } //var propnames = boolProperties.Select(a => a.Name).ToList(); MetricIdentifier micount = new MetricIdentifier(name, "MetricsReportCount"); Metric mcount = tc.GetMetric(micount); mcount.TrackValue(1); foreach (PropertyInfo prop in allProperties.Where(x => x.PropertyType == typeof(bool))) { object val = prop.GetValue(obj, null); Console.WriteLine("{0}={1}", prop.Name, val); if (!bool.TryParse(val.ToString(), out bool boolval)) { continue; } MetricIdentifier mi = new MetricIdentifier(name, prop.Name); Metric metric = tc.GetMetric(mi); metric.TrackValue(boolval ? 1 : 0); } return(true); }
/// <summary> /// Gets the known time series definitions. /// </summary> public static void GetKnownTimeSeriesDefinitions() { // Replace 31280E2F2D2220808315C212DF8062A295B28325 with your cert thumbprint, // install it to the "Personal\Certificates" folder in the "Local Computer" certificate store, // and grant the permission of reading the private key to the service/application using the MDM consumption APIs. string testCertificateThumbprint = "31280E2F2D2220808315C212DF8062A295B28325"; var connectionInfo = new ConnectionInfo(testCertificateThumbprint, StoreLocation.LocalMachine, TimeSpan.FromSeconds(300), MdmEnvironment.Int); var reader = new MetricReader(connectionInfo); string monitoringAccount = "MetricTeamInternalMetrics"; IReadOnlyList <string> namespaces = reader.GetNamespacesAsync(monitoringAccount).Result; string metricNamespace = "PlatformMetrics"; IReadOnlyList <string> metricNames = reader.GetMetricNamesAsync(monitoringAccount, metricNamespace).Result; string metric = "\\Memory\\Available MBytes"; var id = new MetricIdentifier(monitoringAccount, metricNamespace, metric); var dimensions = reader.GetDimensionNamesAsync(id).Result; Console.WriteLine("Dimensions are: {0}", string.Join(", ", dimensions)); var preaggregates = reader.GetPreAggregateConfigurationsAsync(id).Result; foreach (var preAggregateConfiguration in preaggregates) { Console.WriteLine("Pre-aggregate: {0}", JsonConvert.SerializeObject(preAggregateConfiguration)); } var knownTimeSeriesDefinitions = reader.GetKnownTimeSeriesDefinitionsAsync(id, "__Role", DimensionFilter.CreateExcludeFilter("Datacenter", "eastus2")).Result; var roleIndex = knownTimeSeriesDefinitions.GetIndexInDimensionCombination("__Role"); Console.WriteLine("The index of the '__Role' dimension is {0}.", roleIndex); foreach (var value in knownTimeSeriesDefinitions) { Console.WriteLine("Known time series definition: {0}", JsonConvert.SerializeObject(value.DimensionCombination)); } Console.WriteLine("############################ END OF GetKnownTimeSeriesDefinitions ##############################"); }
/// <summary> /// Gets the metric configuration. /// </summary> /// <param name="metricIdentifier">The metric identifier.</param> /// <returns>The metric configuration.</returns> public async Task <MetricConfigurationV2> Get(MetricIdentifier metricIdentifier) { string url = string.Format( "{0}{1}/monitoringAccount/{2}/metricNamespace/{3}/metric/{4}", this.connectionInfo.GetEndpoint(metricIdentifier.MonitoringAccount), this.ConfigRelativeUrl, metricIdentifier.MonitoringAccount, SpecialCharsHelper.EscapeTwice(metricIdentifier.MetricNamespace), SpecialCharsHelper.EscapeTwice(metricIdentifier.MetricName)); var response = await HttpClientHelper.GetResponse( new Uri(url), HttpMethod.Get, this.httpClient, metricIdentifier.MonitoringAccount, this.ConfigRelativeUrl).ConfigureAwait(false); return(JsonConvert.DeserializeObject <MetricConfigurationV2>(response.Item1)); }
/// <summary> /// Gets the single time series. /// </summary> /// <param name="useUserAuth">if set to <c>true</c>, use user authentication; otherwise use certificate authentication.</param> public static void GetSingleTimeSeries(bool useUserAuth) { ConnectionInfo connectionInfo; if (useUserAuth) { connectionInfo = new ConnectionInfo(MdmEnvironment.Int); } else { // Replace 31280E2F2D2220808315C212DF8062A295B28325 with your cert thumbprint, // install it to the "Personal\Certificates" folder in the "Local Computer" certificate store, // and grant the permission of reading the private key to the service/application using the MDM consumption APIs. string testCertificateThumbprint = "C35CBFF9FA6C51E51E1DE97B6D1E246F27661301"; connectionInfo = new ConnectionInfo(new Uri("https://shoebox2.metrics.nsatc.net/public/monitoringAccount/SignalRShoeboxTest/homeStamp"), testCertificateThumbprint, StoreLocation.LocalMachine); } var reader = new MetricReader(connectionInfo); // Single metric var id = new MetricIdentifier("SignalRShoeboxTest", "ShoeboxInternal", "ConnectionCountDelta"); //var id = new MetricIdentifier("SignalRShoeboxTest", "systemLoad", "PodMemory"); // The short link for this series is http://jarvis-int.dc.ad.msft.net/D10A9E2E. var definition = new TimeSeriesDefinition <MetricIdentifier>( id, new Dictionary <string, string> { { "ResourceId", "/subscriptions/5ea15035-434e-46ba-97cd-ea0927a47104/resourceGroups/testsoutheastasia/providers/Microsoft.SignalRService/SignalR/honzhangcenable3" } }); TimeSeries <MetricIdentifier, double?> result = reader.GetTimeSeriesAsync(DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow, SamplingType.Average, definition).Result; foreach (var dataPoint in result.Datapoints) { Console.WriteLine("Time: {0}, Value: {1}", dataPoint.TimestampUtc, dataPoint.Value); } Console.WriteLine("############################ END OF GetSingleTimeSeries ##############################"); }
public void TrackMetric(string metricName, string dimensionName, Dictionary <string, double> values) { if (values is null) { throw new ArgumentNullException(nameof(values)); } if (string.IsNullOrWhiteSpace(metricName)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(metricName)); } var metricDefinition = new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricName, dimensionName); var metric = _telemetryClient.GetMetric(metricDefinition); foreach (var kvp in values) { metric.TrackValue(kvp.Value, kvp.Key); } }
private FilteredTimeSeriesQueryRequest( MetricIdentifier metricIdentifier, IReadOnlyList <string> monitoringAccountNames, string metricNamespace, string metricName, IReadOnlyList <SamplingType> samplingTypes, IReadOnlyList <DimensionFilter> dimensionFilters, DateTime startTimeUtc, DateTime endTimeUtc, int seriesResolutionInMinutes, AggregationType aggregationType, PropertyDefinition topPropertyDefinition, int numberOfResultsToReturn, OrderBy orderBy, bool zeroAsNoValueSentinel, bool aggregateAcrossAccounts, IReadOnlyList <string> outputDimensionNames = null, bool lastValueMode = false) { this.MetricIdentifier = metricIdentifier; this.MonitoringAccountNames = monitoringAccountNames; this.MetricNamespace = metricNamespace; this.MetricName = metricName; this.SamplingTypes = samplingTypes; this.DimensionFilters = dimensionFilters; this.StartTimeUtc = startTimeUtc; this.EndTimeUtc = endTimeUtc; this.SeriesResolutionInMinutes = seriesResolutionInMinutes; this.AggregationType = aggregationType; this.TopPropertyDefinition = topPropertyDefinition; this.NumberOfResultsToReturn = numberOfResultsToReturn; this.OrderBy = orderBy; this.ZeroAsNoValueSentinel = zeroAsNoValueSentinel; this.AggregateAcrossAccounts = aggregateAcrossAccounts; this.OutputDimensionNames = outputDimensionNames; this.LastValueMode = lastValueMode; }
public SeriesMetadata(MetricIdentifier metricIdentifier, string[] dimensionNames) { this.MetricIdentifier = metricIdentifier; this.DimensionNames = dimensionNames; }
static void Main() { //for some fun try out this command line parameter: chummer://plugin:SINners:Load:5ff55b9d-7d1c-4067-a2f5-774127346f4e PageViewTelemetry pvt = null; var startTime = DateTimeOffset.UtcNow; using (GlobalChummerMutex = new Mutex(false, @"Global\" + strChummerGuid)) { // Set default cultures based on the currently set language CultureInfo.DefaultThreadCurrentCulture = GlobalOptions.CultureInfo; CultureInfo.DefaultThreadCurrentUICulture = GlobalOptions.CultureInfo; string strPostErrorMessage = string.Empty; string settingsDirectoryPath = Path.Combine(Utils.GetStartupPath, "settings"); if (!Directory.Exists(settingsDirectoryPath)) { try { Directory.CreateDirectory(settingsDirectoryPath); } catch (UnauthorizedAccessException ex) { string strMessage = LanguageManager.GetString("Message_Insufficient_Permissions_Warning", GlobalOptions.Language, false); if (string.IsNullOrEmpty(strMessage)) { strMessage = ex.ToString(); } strPostErrorMessage = strMessage; } catch (Exception ex) { strPostErrorMessage = ex.ToString(); } } IsMono = Type.GetType("Mono.Runtime") != null; // Mono doesn't always play nice with ProfileOptimization, so it's better to just not bother with it when running under Mono if (!IsMono) { ProfileOptimization.SetProfileRoot(Utils.GetStartupPath); ProfileOptimization.StartProfile("chummerprofile"); } Stopwatch sw = Stopwatch.StartNew(); //If debugging and launched from other place (Bootstrap), launch debugger if (Environment.GetCommandLineArgs().Contains("/debug") && !Debugger.IsAttached) { Debugger.Launch(); } sw.TaskEnd("dbgchk"); //Various init stuff (that mostly "can" be removed as they serve //debugging more than function //Needs to be called before Log is setup, as it moves where log might be. FixCwd(); sw.TaskEnd("fixcwd"); AppDomain.CurrentDomain.FirstChanceException += ExceptionHeatMap.OnException; sw.TaskEnd("appdomain 2"); string strInfo = string.Format(GlobalOptions.InvariantCultureInfo, "Application Chummer5a build {0} started at {1} with command line arguments {2}", Assembly.GetExecutingAssembly().GetName().Version, DateTime.UtcNow, Environment.CommandLine); sw.TaskEnd("infogen"); sw.TaskEnd("infoprnt"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sw.TaskEnd("languagefreestartup"); #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (o, e) => { if (e.ExceptionObject is Exception ex) { CrashHandler.WebMiniDumpHandler(ex); } //main.Hide(); //main.ShowInTaskbar = false; }; #else AppDomain.CurrentDomain.UnhandledException += (o, e) => { try { if (e.ExceptionObject is Exception myException) { myException.Data.Add("IsCrash", bool.TrueString); ExceptionTelemetry et = new ExceptionTelemetry(myException) { SeverityLevel = SeverityLevel.Critical }; //we have to enable the uploading of THIS message, so it isn't filtered out in the DropUserdataTelemetryProcessos foreach (DictionaryEntry d in myException.Data) { if (d.Key != null && d.Value != null) { et.Properties.Add(d.Key.ToString(), d.Value.ToString()); } } ChummerTelemetryClient.TrackException(myException); ChummerTelemetryClient.Flush(); } } catch (Exception exception) { Console.WriteLine(exception); } }; #endif sw.TaskEnd("Startup"); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); if (!string.IsNullOrEmpty(LanguageManager.ManagerErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(LanguageManager.ManagerErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!string.IsNullOrEmpty(GlobalOptions.ErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(GlobalOptions.ErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!string.IsNullOrEmpty(strPostErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(strPostErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { TelemetryConfiguration.Active.InstrumentationKey = "012fd080-80dc-4c10-97df-4f2cf8c805d5"; LogManager.ThrowExceptions = true; if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyMetric) { ConfigurationItemFactory.Default.Targets.RegisterDefinition( "ApplicationInsightsTarget", typeof(ApplicationInsightsTarget) ); } LogManager.ThrowExceptions = false; Log = LogManager.GetCurrentClassLogger(); if (GlobalOptions.UseLogging) { foreach (LoggingRule objRule in LogManager.Configuration.LoggingRules) { #if DEBUG //enable logging to EventLog when Debugging if (objRule.Levels.Count == 0 && objRule.RuleName == "ELChummer") { objRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal); } #endif //only change the loglevel, if it's off - otherwise it has been changed manually if (objRule.Levels.Count == 0) { objRule.EnableLoggingForLevels(LogLevel.Debug, LogLevel.Fatal); } } } if (Properties.Settings.Default.UploadClientId == Guid.Empty) { Properties.Settings.Default.UploadClientId = Guid.NewGuid(); Properties.Settings.Default.Save(); } if (!Utils.IsUnitTest && GlobalOptions.UseLoggingApplicationInsights >= UseAILogging.OnlyMetric) { #if DEBUG //If you set true as DeveloperMode (see above), you can see the sending telemetry in the debugging output window in IDE. TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true; #else TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = false; #endif TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomTelemetryInitializer()); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use(next => new TranslateExceptionTelemetryProcessor(next)); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use(next => new DropUserdataTelemetryProcessor(next, Environment.UserName)); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Build(); //for now lets disable live view.We may make another GlobalOption to enable it at a later stage... //var live = new LiveStreamProvider(ApplicationInsightsConfig); //live.Enable(); //Log an Event with AssemblyVersion and CultureInfo MetricIdentifier objMetricIdentifier = new MetricIdentifier("Chummer", "Program Start", "Version", "Culture", dimension3Name: "AISetting", dimension4Name: "OSVersion"); string strOSVersion = helpers.Application_Insights.OSVersion.GetOSInfo(); Metric objMetric = ChummerTelemetryClient.GetMetric(objMetricIdentifier); objMetric.TrackValue(1, Assembly.GetExecutingAssembly().GetName().Version.ToString(), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, GlobalOptions.UseLoggingApplicationInsights.ToString(), strOSVersion); //Log a page view: pvt = new PageViewTelemetry("frmChummerMain()") { Name = "Chummer Startup: " + Assembly.GetExecutingAssembly().GetName().Version, Id = Properties.Settings.Default.UploadClientId.ToString(), Timestamp = startTime }; pvt.Context.Operation.Name = "Operation Program.Main()"; pvt.Properties.Add("parameters", Environment.CommandLine); UploadObjectAsMetric.UploadObject(ChummerTelemetryClient, typeof(GlobalOptions)); } else { TelemetryConfiguration.Active.DisableTelemetry = true; } Log.Info(strInfo); Log.Info("Logging options are set to " + GlobalOptions.UseLogging + " and Upload-Options are set to " + GlobalOptions.UseLoggingApplicationInsights + " (Installation-Id: " + Properties.Settings.Default.UploadClientId.ToString("D", GlobalOptions.InvariantCultureInfo) + ")."); //make sure the Settings are upgraded/preserved after an upgrade //see for details: https://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net/534335#534335 if (Properties.Settings.Default.UpgradeRequired) { if (UnblockPath(AppDomain.CurrentDomain.BaseDirectory)) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } else { Log.Warn("Files could not be unblocked in " + AppDomain.CurrentDomain.BaseDirectory); } } } catch (Exception e) { Console.WriteLine(e); Log.Error(e); #if DEBUG throw; #endif } //load the plugins and maybe work of any command line arguments //arguments come in the form of // /plugin:Name:Parameter:Argument // /plugin:SINners:RegisterUriScheme:0 bool showMainForm = !Utils.IsUnitTest; // Make sure the default language has been loaded before attempting to open the Main Form. LanguageManager.LoadLanguage(GlobalOptions.Language); MainForm = new frmChummerMain(); try { PluginLoader.LoadPlugins(null); } catch (ApplicationException) { showMainForm = false; } if (!Utils.IsUnitTest) { string[] strArgs = Environment.GetCommandLineArgs(); try { // Process plugin args synchronously because plugin load order can end up mattering foreach (string strArg in strArgs) { if (!strArg.Contains("/plugin")) { continue; } if (!GlobalOptions.PluginsEnabled) { string strMessage = "Please enable Plugins to use command-line arguments invoking specific plugin-functions!"; Log.Warn(strMessage); MainForm.ShowMessageBox(strMessage, "Plugins not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { string strWhatPlugin = strArg.Substring(strArg.IndexOf("/plugin", StringComparison.Ordinal) + 8); //some external apps choose to add a '/' before a ':' even in the middle of an url... strWhatPlugin = strWhatPlugin.TrimStart(':'); int intEndPlugin = strWhatPlugin.IndexOf(':'); string strParameter = strWhatPlugin.Substring(intEndPlugin + 1); strWhatPlugin = strWhatPlugin.Substring(0, intEndPlugin); IPlugin objActivePlugin = PluginLoader.MyActivePlugins.FirstOrDefault(a => a.ToString() == strWhatPlugin); if (objActivePlugin == null) { if (PluginLoader.MyPlugins.All(a => a.ToString() != strWhatPlugin)) { string strMessage = "Plugin " + strWhatPlugin + " is not enabled in the options!" + Environment.NewLine + "If you want to use command-line arguments, please enable this plugin and restart the program."; Log.Warn(strMessage); MainForm.ShowMessageBox(strMessage, strWhatPlugin + " not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { showMainForm &= objActivePlugin.ProcessCommandLine(strParameter); } } } } catch (Exception e) { ExceptionTelemetry ex = new ExceptionTelemetry(e) { SeverityLevel = SeverityLevel.Warning }; ChummerTelemetryClient?.TrackException(ex); Log.Warn(e); } } if (showMainForm) { MainForm.MyStartupPVT = pvt; Application.Run(MainForm); } PluginLoader?.Dispose(); Log.Info(ExceptionHeatMap.GenerateInfo()); if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyLocal && ChummerTelemetryClient != null) { ChummerTelemetryClient.Flush(); //we have to wait a bit to give it time to upload the data Console.WriteLine("Waiting a bit to flush logging data..."); Thread.Sleep(2000); } } }
public static void LogMetric(this Common.Telemetry.Metric metric, TelemetryClient telemetryClient, double metricValue) { EnsureArg.IsNotNull(metric); EnsureArg.IsNotNull(telemetryClient); var metricName = metric.Name; var dimensions = metric.Dimensions; var dimensionNumber = metric.Dimensions.Count; if (dimensionNumber > 10) { telemetryClient.TrackException( new Exception($"Metric {metricName} exceeds the amount of allowed dimensions")); return; } string[] dimNames = new string[dimensions.Count]; dimensions.Keys.CopyTo(dimNames, 0); string[] dimValues = new string[dimNames.Length]; int count = 0; foreach (string dimName in dimNames) { dimValues[count] = dimensions[dimName].ToString(); count++; } dimensions.Values.CopyTo(dimValues, 0); switch (dimensionNumber) { case 0: telemetryClient .GetMetric( metricName) .TrackValue( metricValue); break; case 1: telemetryClient .GetMetric( metricName, dimNames[0]) .TrackValue( metricValue, dimValues[0]); break; case 2: telemetryClient .GetMetric( metricName, dimNames[0], dimNames[1]) .TrackValue( metricValue, dimValues[0], dimValues[1]); break; case 3: telemetryClient .GetMetric( metricName, dimNames[0], dimNames[1], dimNames[2]) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2]); break; case 4: telemetryClient .GetMetric( metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3]) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3]); break; case 5: var metric5DId = new MetricIdentifier( _namespace, metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3], dimNames[4]); telemetryClient .GetMetric(metric5DId) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3], dimValues[4]); break; case 6: var metric6DId = new MetricIdentifier( _namespace, metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3], dimNames[4], dimNames[5]); telemetryClient .GetMetric(metric6DId) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3], dimValues[4], dimValues[5]); break; case 7: var metric7DId = new MetricIdentifier( _namespace, metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3], dimNames[4], dimNames[5], dimNames[6]); telemetryClient .GetMetric(metric7DId) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3], dimValues[4], dimValues[5], dimValues[6]); break; case 8: var metric8DId = new MetricIdentifier( _namespace, metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3], dimNames[4], dimNames[5], dimNames[6], dimNames[7]); telemetryClient .GetMetric(metric8DId) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3], dimValues[4], dimValues[5], dimValues[6], dimValues[7]); break; case 9: var metric9DId = new MetricIdentifier( _namespace, metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3], dimNames[4], dimNames[5], dimNames[6], dimNames[7], dimNames[8]); telemetryClient .GetMetric(metric9DId) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3], dimValues[4], dimValues[5], dimValues[6], dimValues[7], dimValues[8]); break; case 10: var metric10DId = new MetricIdentifier( _namespace, metricName, dimNames[0], dimNames[1], dimNames[2], dimNames[3], dimNames[4], dimNames[5], dimNames[6], dimNames[7], dimNames[8], dimNames[9]); telemetryClient .GetMetric(metric10DId) .TrackValue( metricValue, dimValues[0], dimValues[1], dimValues[2], dimValues[3], dimValues[4], dimValues[5], dimValues[6], dimValues[7], dimValues[8], dimValues[9]); break; default: break; } }