Esempio n. 1
0
        public async Task BatchQuery()
        {
            #region Snippet:BatchQuery

#if SNIPPET
            Uri    endpoint    = new Uri("https://api.loganalytics.io");
            string workspaceId = "<workspace_id>";
#else
            Uri    endpoint    = TestEnvironment.LogsEndpoint;
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            LogsQueryClient client = new LogsQueryClient(endpoint, new DefaultAzureCredential());

            // Query TOP 10 resource groups by event count
            // And total event count
            LogsBatchQuery batch        = new LogsBatchQuery();
            string         countQueryId = batch.AddQuery(workspaceId, "AzureActivity | count", TimeSpan.FromDays(1));
            string         topQueryId   = batch.AddQuery(workspaceId, "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count", TimeSpan.FromDays(1));

            Response <LogsBatchQueryResult> response = await client.QueryBatchAsync(batch);

            var count      = response.Value.GetResult <int>(countQueryId).Single();
            var topEntries = response.Value.GetResult <MyLogEntryModel>(topQueryId);

            Console.WriteLine($"AzureActivity has total {count} events");
            foreach (var logEntryModel in topEntries)
            {
                Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
            }

            #endregion
        }
        public async Task QueryLogsAsPrimitive()
        {
            #region Snippet:QueryLogsAsPrimitive

#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            var client = new LogsQueryClient(new DefaultAzureCredential());

            // Query TOP 10 resource groups by event count
            #region Snippet:QueryLogsAsPrimitiveCall
            Response <IReadOnlyList <string> > response = await client.QueryWorkspaceAsync <string>(
                workspaceId,
                "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count | project ResourceGroup",
                new QueryTimeRange(TimeSpan.FromDays(1)));

            #endregion

            foreach (var resourceGroup in response.Value)
            {
                Console.WriteLine(resourceGroup);
            }

            #endregion
        }
        public async Task QueryLogsWithPartialSuccess()
        {
            var client = new LogsQueryClient(new DefaultAzureCredential());

            #region Snippet:QueryLogsWithPartialSuccess
            Response <LogsQueryResult> response = await client.QueryWorkspaceAsync(
                TestEnvironment.WorkspaceId,
                "My Not So Valid Query",
                new QueryTimeRange(TimeSpan.FromDays(1)),
                new LogsQueryOptions
            {
                AllowPartialErrors = true
            });

            LogsQueryResult result = response.Value;

            if (result.Status == LogsQueryResultStatus.PartialFailure)
            {
                var errorCode    = result.Error.Code;
                var errorMessage = result.Error.Message;

                // code omitted for brevity
            }
            #endregion
        }
        public async Task QueryLogsAsTable()
        {
            #region Snippet:QueryLogsAsTable
#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif
            #region Snippet:CreateLogsClient
            var client = new LogsQueryClient(new DefaultAzureCredential());
            #endregion
            Response <LogsQueryResult> response = await client.QueryWorkspaceAsync(
                workspaceId,
                "AzureActivity | top 10 by TimeGenerated",
                new QueryTimeRange(TimeSpan.FromDays(1)));

            LogsTable table = response.Value.Table;

            foreach (var row in table.Rows)
            {
                Console.WriteLine(row["OperationName"] + " " + row["ResourceGroup"]);
            }

            #endregion
        }
Esempio n. 5
0
        public async Task QueryLogsWithTimeout()
        {
            #region Snippet:QueryLogsWithTimeout
#if SNIPPET
            Uri    endpoint    = new Uri("https://api.loganalytics.io");
            string workspaceId = "<workspace_id>";
#else
            Uri    endpoint    = TestEnvironment.LogsEndpoint;
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            LogsQueryClient client = new LogsQueryClient(endpoint, new DefaultAzureCredential());

            // Query TOP 10 resource groups by event count
            Response <IReadOnlyList <int> > response = await client.QueryAsync <int>(workspaceId,
                                                                                     "AzureActivity | summarize count()",
                                                                                     TimeSpan.FromDays(1),
                                                                                     options : new LogsQueryOptions()
            {
                ServerTimeout = TimeSpan.FromMinutes(10)
            });

            foreach (var resourceGroup in response.Value)
            {
                Console.WriteLine(resourceGroup);
            }

            #endregion
        }
Esempio n. 6
0
        public async Task UsesDefaultAuthScope(string scope, string expectedScope)
        {
            var mockTransport = MockTransport.FromMessageCallback(message =>
            {
                var mockResponse = new MockResponse(200);
                mockResponse.SetContent("{\"tables\":[]}");
                return(mockResponse);
            });

            Mock <MockCredential> mock = new() { CallBase = true };

            string[] scopes = null;
            mock.Setup(m => m.GetTokenAsync(It.IsAny <TokenRequestContext>(), It.IsAny <CancellationToken>()))
            .Callback <TokenRequestContext, CancellationToken>((c, _) => scopes = c.Scopes)
            .CallBase();

            var client = new LogsQueryClient(mock.Object, new LogsQueryClientOptions()
            {
                Transport           = mockTransport,
                AuthenticationScope = scope
            });

            await client.QueryAsync("", "", DateTimeRange.All);

            Assert.AreEqual(new[] { expectedScope }, scopes);
        }
    }
        public async Task QueryLogsWithVisualization()
        {
            #region Snippet:QueryLogsWithVisualization
#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif
            var client = new LogsQueryClient(new DefaultAzureCredential());

            Response <LogsQueryResult> response = await client.QueryWorkspaceAsync(
                workspaceId,
                @"StormEvents
                    | summarize event_count = count() by State
                    | where event_count > 10
                    | project State, event_count
                    | render columnchart",
                new QueryTimeRange(TimeSpan.FromDays(1)),
                new LogsQueryOptions
            {
                IncludeVisualization = true,
            });

            BinaryData viz = response.Value.GetVisualization();
            using var vizDoc = JsonDocument.Parse(viz);
            var queryViz = vizDoc.RootElement.GetProperty("visualization");
            Console.WriteLine(queryViz.GetString());

            #endregion
        }
Esempio n. 8
0
        public async Task QueryLogsAsPrimitive()
        {
            #region Snippet:QueryLogsAsPrimitive

#if SNIPPET
            Uri    endpoint    = new Uri("https://api.loganalytics.io");
            string workspaceId = "<workspace_id>";
#else
            Uri    endpoint    = TestEnvironment.LogsEndpoint;
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            LogsQueryClient client = new LogsQueryClient(endpoint, new DefaultAzureCredential());

            // Query TOP 10 resource groups by event count
            Response <IReadOnlyList <string> > response = await client.QueryAsync <string>(workspaceId,
                                                                                           "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count | project ResourceGroup",
                                                                                           TimeSpan.FromDays(1));

            foreach (var resourceGroup in response.Value)
            {
                Console.WriteLine(resourceGroup);
            }

            #endregion
        }
        public void CanSetServiceTimeout_Mocked()
        {
            string   preferHeader    = null;
            TimeSpan?networkOverride = default;

            var mockTransport = MockTransport.FromMessageCallback(message =>
            {
                Assert.True(message.Request.Headers.TryGetValue("prefer", out preferHeader));
                networkOverride = message.NetworkTimeout;

                return(new MockResponse(403));
            });

            var client = new LogsQueryClient(new Uri("https://api.loganalytics.io"), new MockCredential(), new LogsQueryClientOptions()
            {
                Transport = mockTransport
            });

            Assert.ThrowsAsync <RequestFailedException>(() => client.QueryWorkspaceAsync("wid", "tid", TimeSpan.FromDays(1), options: new LogsQueryOptions()
            {
                ServerTimeout = TimeSpan.FromMinutes(10)
            }));

            Assert.AreEqual("wait=600", preferHeader);
            // The network timeout is adjusted with 15 sec buffer
            Assert.AreEqual(TimeSpan.FromMinutes(10).Add(TimeSpan.FromSeconds(15)), networkOverride);
        }
        public async Task QueryLogsWithAdditionalWorkspace()
        {
            #region Snippet:QueryLogsWithAdditionalWorkspace
#if SNIPPET
            string workspaceId           = "<workspace_id>";
            string additionalWorkspaceId = "<additional_workspace_id>";
#else
            string workspaceId           = TestEnvironment.WorkspaceId;
            string additionalWorkspaceId = TestEnvironment.WorkspaceId;
#endif

            var client = new LogsQueryClient(new DefaultAzureCredential());

            // Query TOP 10 resource groups by event count
            Response <IReadOnlyList <int> > response = await client.QueryWorkspaceAsync <int>(
                workspaceId,
                "AzureActivity | summarize count()",
                new QueryTimeRange(TimeSpan.FromDays(1)),
                options : new LogsQueryOptions
            {
                AdditionalWorkspaces = { additionalWorkspaceId }
            });

            foreach (var resourceGroup in response.Value)
            {
                Console.WriteLine(resourceGroup);
            }

            #endregion
        }
        public async Task QueryLogsAsModels()
        {
            #region Snippet:QueryLogsAsModels

#if SNIPPET
            var    client      = new LogsQueryClient(new DefaultAzureCredential());
            string workspaceId = "<workspace_id>";
#else
            var    client      = new LogsQueryClient(TestEnvironment.LogsEndpoint, new DefaultAzureCredential());
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            // Query TOP 10 resource groups by event count
            #region Snippet:QueryLogsAsModelCall
            Response <IReadOnlyList <MyLogEntryModel> > response = await client.QueryWorkspaceAsync <MyLogEntryModel>(
                workspaceId,
                "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
                new QueryTimeRange(TimeSpan.FromDays(1)));

            #endregion

            foreach (var logEntryModel in response.Value)
            {
                Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
            }

            #endregion
        }
        public async Task QueryLogsWithStatistics()
        {
            #region Snippet:QueryLogsWithStatistics
#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif
            var client = new LogsQueryClient(new DefaultAzureCredential());

            Response <LogsQueryResult> response = await client.QueryWorkspaceAsync(
                workspaceId,
                "AzureActivity | top 10 by TimeGenerated",
                new QueryTimeRange(TimeSpan.FromDays(1)),
                new LogsQueryOptions
            {
                IncludeStatistics = true,
            });

            BinaryData stats = response.Value.GetStatistics();
            using var statsDoc = JsonDocument.Parse(stats);
            var queryStats = statsDoc.RootElement.GetProperty("query");
            Console.WriteLine(queryStats.GetProperty("executionTime").GetDouble());

            #endregion
        }
        public async Task <bool> RunLAQuery(string tableName)
        {
            try
            {
                // Get credentials from config.txt
                Dictionary <string, string> credentials = new AppConfig().GetCredentials();
                _workspaceId  = credentials["workspaceId"];
                _clientId     = credentials["clientId"];
                _clientSecret = credentials["clientSecret"];
                _domain       = credentials["domain"];

                var credential = new ClientSecretCredential(_domain, _clientId, _clientSecret);
                var logsClient = new LogsQueryClient(credential);

                // Get a list of table names in your workspace
                var distinctTablesQuery             = "search * | distinct $table";
                Response <LogsQueryResult> response =
                    await logsClient.QueryWorkspaceAsync(_workspaceId, distinctTablesQuery, QueryTimeRange.All);

                LogsTable table = response.Value.Table;

                IEnumerable <string> tableNames = from row in table.Rows
                                                  let columnValue = row.GetString("$table")
                                                                    where columnValue.EndsWith("_CL")
                                                                    select columnValue;

                // Get custom table name
                tableName = tableName.Replace(".json", "");

                // Check if the custom table name exists in the list
                if (!tableNames.Contains(tableName))
                {
                    return(false);
                }
                else
                {
                    // Check if there's any data in the table for last 7 days
                    var query     = $"{tableName} | limit 10";
                    var timeRange = new QueryTimeRange(TimeSpan.FromDays(7));
                    Response <LogsQueryResult> results =
                        await logsClient.QueryWorkspaceAsync(_workspaceId, query, timeRange);

                    int tableCount = results.Value.AllTables.Count;

                    return(tableCount > 0);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Calling Log Analytics error " + ex.Message);
            }
        }
Esempio n. 14
0
        protected MonitorQueryPerfTest(T options) : base(options)
        {
            LogsQueryClient = new LogsQueryClient(
                TestEnvironment.LogsEndpoint,
                TestEnvironment.Credential,
                ConfigureClientOptions(new LogsQueryClientOptions()));

            MetricsQueryClient = new MetricsQueryClient(
                TestEnvironment.MetricsEndpoint,
                TestEnvironment.Credential,
                ConfigureClientOptions(new MetricsQueryClientOptions())
                );
        }
        public async Task UsesDefaultEndpoint()
        {
            var mockTransport = MockTransport.FromMessageCallback(_ =>
            {
                var mockResponse = new MockResponse(200);
                mockResponse.SetContent("{\"tables\":[]}");
                return(mockResponse);
            });

            var client = new LogsQueryClient(new MockCredential(), new LogsQueryClientOptions()
            {
                Transport = mockTransport
            });

            await client.QueryWorkspaceAsync("", "", QueryTimeRange.All);

            StringAssert.StartsWith("https://api.loganalytics.io", mockTransport.SingleRequest.Uri.ToString());
        }
Esempio n. 16
0
        private async Task <bool> LoadExceptionsAsync(LogsQueryClient client, List <Api.LogItem> items, QueryTimeRange queryTimeRange, string filter)
        {
            var extend = filter.IsNullOrEmpty() ? null : $"| extend RequestId = Properties.RequestId | extend RequestPath = Properties.RequestPath {GetGeneralQueryExtend()}";

            var where = filter.IsNullOrEmpty() ? null : $"| where Details contains '{filter}' or RequestId contains '{filter}' or RequestPath contains '{filter}' or {GetGeneralQueryWhere(filter)}";
            var exceptionsQuery = GetQuery("AppExceptions", extend, where);
            Response <LogsQueryResult> response = await client.QueryWorkspaceAsync(settings.ApplicationInsights.WorkspaceId, exceptionsQuery, queryTimeRange);

            var table = response.Value.Table;

            foreach (var row in table.Rows)
            {
                var item = new Api.LogItem
                {
                    Type = row.GetInt32(Constants.Logs.Results.SeverityLevel) switch
                    {
                        4 => Api.LogItemTypes.CriticalError,
                        3 => Api.LogItemTypes.Error,
                        _ => Api.LogItemTypes.Warning
                    },
        public async Task BatchQuery()
        {
            #region Snippet:BatchQuery

#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            var client = new LogsQueryClient(new DefaultAzureCredential());

            // Query TOP 10 resource groups by event count
            // And total event count
            var batch = new LogsBatchQuery();

            #region Snippet:BatchQueryAddAndGet
            string countQueryId = batch.AddWorkspaceQuery(
                workspaceId,
                "AzureActivity | count",
                new QueryTimeRange(TimeSpan.FromDays(1)));
            string topQueryId = batch.AddWorkspaceQuery(
                workspaceId,
                "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
                new QueryTimeRange(TimeSpan.FromDays(1)));

            Response <LogsBatchQueryResultCollection> response = await client.QueryBatchAsync(batch);

            var count      = response.Value.GetResult <int>(countQueryId).Single();
            var topEntries = response.Value.GetResult <MyLogEntryModel>(topQueryId);
            #endregion

            Console.WriteLine($"AzureActivity has total {count} events");
            foreach (var logEntryModel in topEntries)
            {
                Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
            }

            #endregion
        }
        public async Task BadRequest()
        {
            #region Snippet:BadRequest
#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            var client = new LogsQueryClient(new DefaultAzureCredential());

            try
            {
                await client.QueryWorkspaceAsync(
                    workspaceId, "My Not So Valid Query", new QueryTimeRange(TimeSpan.FromDays(1)));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            #endregion
        }
        public async Task QueryLogsAsTablePrintAll()
        {
            #region Snippet:QueryLogsPrintTable

#if SNIPPET
            string workspaceId = "<workspace_id>";
#else
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            var client = new LogsQueryClient(new DefaultAzureCredential());
            Response <LogsQueryResult> response = await client.QueryWorkspaceAsync(
                workspaceId,
                "AzureActivity | top 10 by TimeGenerated",
                new QueryTimeRange(TimeSpan.FromDays(1)));

            LogsTable table = response.Value.Table;

            foreach (var column in table.Columns)
            {
                Console.Write(column.Name + ";");
            }

            Console.WriteLine();

            var columnCount = table.Columns.Count;
            foreach (var row in table.Rows)
            {
                for (int i = 0; i < columnCount; i++)
                {
                    Console.Write(row[i] + ";");
                }

                Console.WriteLine();
            }

            #endregion
        }
Esempio n. 20
0
        public async Task BadRequest()
        {
            #region Snippet:BadRequest
#if SNIPPET
            Uri    endpoint    = new Uri("https://api.loganalytics.io");
            string workspaceId = "<workspace_id>";
#else
            Uri    endpoint    = TestEnvironment.LogsEndpoint;
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            LogsQueryClient client = new LogsQueryClient(endpoint, new DefaultAzureCredential());

            try
            {
                await client.QueryAsync(workspaceId, "My Not So Valid Query", TimeSpan.FromDays(1));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            #endregion
        }
Esempio n. 21
0
        public async Task QueryLogsAsTable()
        {
            #region Snippet:QueryLogsAsTable
#if SNIPPET
            Uri    endpoint    = new Uri("https://api.loganalytics.io");
            string workspaceId = "<workspace_id>";
#else
            Uri    endpoint    = TestEnvironment.LogsEndpoint;
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            LogsQueryClient            client   = new LogsQueryClient(endpoint, new DefaultAzureCredential());
            Response <LogsQueryResult> response = await client.QueryAsync(workspaceId, "AzureActivity | top 10 by TimeGenerated", TimeSpan.FromDays(1));

            LogsQueryResultTable table = response.Value.PrimaryTable;

            foreach (var row in table.Rows)
            {
                Console.WriteLine(row["OperationName"] + " " + row["ResourceGroup"]);
            }

            #endregion
        }
Esempio n. 22
0
        public async Task QueryLogsAsTablePrintAll()
        {
            #region Snippet:QueryLogsPrintTable

#if SNIPPET
            Uri    endpoint    = new Uri("https://api.loganalytics.io");
            string workspaceId = "<workspace_id>";
#else
            Uri    endpoint    = TestEnvironment.LogsEndpoint;
            string workspaceId = TestEnvironment.WorkspaceId;
#endif

            LogsQueryClient            client   = new LogsQueryClient(endpoint, new DefaultAzureCredential());
            Response <LogsQueryResult> response = await client.QueryAsync(workspaceId, "AzureActivity | top 10 by TimeGenerated", TimeSpan.FromDays(1));

            LogsQueryResultTable table = response.Value.PrimaryTable;

            foreach (var column in table.Columns)
            {
                Console.Write(column.Name + ";");
            }

            Console.WriteLine();

            var columnCount = table.Columns.Count;
            foreach (var row in table.Rows)
            {
                for (int i = 0; i < columnCount; i++)
                {
                    Console.Write(row[i] + ";");
                }

                Console.WriteLine();
            }

            #endregion
        }
        public async Task QueryBatchHandledInvalidResponse()
        {
            var badResponse   = @"{
    ""responses"": [
        {
            ""id"": ""0"",
            ""status"": 200,
            ""headers"": {
                ""Age"": ""3"",
                ""request-context"": ""appId=cid-v1:70941e4f-7e8f-40b7-b730-183893db0297""
            },
            ""body"": ""{\""tables\"":[{\""name\"":\""PrimaryResult\"",\""columns\"":[{\""name\"":\""TenantId\"",\""type\"":\""string\""},{\""name\"":\""SourceSystem\"",\""type\"":\""string\""},{\""name\"":\""MG\"",\""type\"":\""string\""},{\""name\"":\""ManagementGroupName\"",\""type\"":\""string\""},{\""name\"":\""TimeGenerated\"",\""type\"":\""datetime\""},{\""name\"":\""Computer\"",\""type\"":\""string\""},{\""name\"":\""RawData\"",\""type\"":\""string\""},{\""name\"":\""IntColumn_d\"",\""type\"":\""real\""},{\""name\"":\""StringColumn_s\"",\""type\"":\""string\""},{\""name\"":\""BoolColumn_b\"",\""type\"":\""bool\""},{\""name\"":\""FloatColumn_d\"",\""type\"":\""real\""},{\""name\"":\""Type\"",\""type\"":\""string\""},{\""name\"":\""_ResourceId\"",\""type\"":\""string\""}],\""rows\"":[[\""e7bf7412-576d-4978-b47c-2edf669e3e2a\"",\""RestAPI\"",\""\"",\""\"",\""2021-05-31T00:00:00Z\"",\""\"",\""\"",1,\""a\"",false,0,\""TableA1_151_CL\"",\""\""],[\""e7bf7412-576d-4978-b47c-2edf669e3e2a\"",\""RestAPI\"",\""\"",\""\"",\""2021-06-02T00:00:00Z\"",\""\"",\""\"",3,\""b\"",true,1.20000005,\""TableA1_151_CL\"",\""\""],[\""e7bf7412-576d-4978-b47c-2edf669e3e2a\"",\""RestAPI\"",\""\"",\""\"",\""2021-06-05T00:00:00Z\"",\""\"",\""\"",1,\""c\"",false,1.10000002,\""TableA1_151_CL\"",\""\""]]}]}""
        }
    ]
}
";
            var mockTransport = MockTransport.FromMessageCallback(message =>
            {
                var mockResponse = new MockResponse(200);
                mockResponse.SetContent(badResponse);
                return(mockResponse);
            });

            var client = new LogsQueryClient(new Uri("https://api.loganalytics.io"), new MockCredential(), new LogsQueryClientOptions()
            {
                Transport = mockTransport
            });

            LogsBatchQuery batch = new LogsBatchQuery();

            batch.AddWorkspaceQuery("wid", "query", QueryTimeRange.All);

            LogsBatchQueryResultCollection batchResults = await client.QueryBatchAsync(batch);

            Assert.NotNull(batchResults.GetResult("0"));
        }
        public void ExposesPublicEndpoint()
        {
            var client = new LogsQueryClient(new Uri("https://api.loganalytics.io"), new MockCredential(), new LogsQueryClientOptions());

            Assert.AreEqual(new Uri("https://api.loganalytics.io"), client.Endpoint);
        }
Esempio n. 25
0
 public override void Run(CancellationToken cancellationToken)
 {
     LogsQueryClient.Query <TestModelForTypes>(TestEnvironment.WorkspaceId, LogsQuery, DateTimeRange.All, cancellationToken: cancellationToken);
 }
Esempio n. 26
0
 public override async Task RunAsync(CancellationToken cancellationToken)
 {
     await LogsQueryClient.QueryAsync <TestModelForTypes>(TestEnvironment.WorkspaceId, LogsQuery, DateTimeRange.All, cancellationToken : cancellationToken).ConfigureAwait(false);
 }
Esempio n. 27
0
        public async Task <ActionResult <Api.LogResponse> > GetTrackLog(Api.LogRequest logRequest)
        {
            try
            {
                if (!await ModelState.TryValidateObjectAsync(logRequest))
                {
                    return(BadRequest(ModelState));
                }

                if (!logRequest.QueryExceptions && !logRequest.QueryTraces && !logRequest.QueryEvents && !logRequest.QueryMetrics)
                {
                    logRequest.QueryExceptions = true;
                    logRequest.QueryEvents     = true;
                }

                var client = new LogsQueryClient(tokenCredential);

                var queryTimeRange = new QueryTimeRange(DateTimeOffset.FromUnixTimeSeconds(logRequest.FromTime), DateTimeOffset.FromUnixTimeSeconds(logRequest.ToTime));

                var responseTruncated = false;
                var items             = new List <Api.LogItem>();
                if (logRequest.QueryExceptions)
                {
                    if (await LoadExceptionsAsync(client, items, queryTimeRange, logRequest.Filter))
                    {
                        responseTruncated = true;
                    }
                }
                if (logRequest.QueryTraces)
                {
                    if (await LoadTracesAsync(client, items, queryTimeRange, logRequest.Filter))
                    {
                        responseTruncated = true;
                    }
                }
                if (logRequest.QueryEvents)
                {
                    if (await LoadEventsAsync(client, items, queryTimeRange, logRequest.Filter))
                    {
                        responseTruncated = true;
                    }
                }
                if (logRequest.QueryMetrics)
                {
                    if (await LoadMetricsAsync(client, items, queryTimeRange, logRequest.Filter))
                    {
                        responseTruncated = true;
                    }
                }

                if (items.Count() >= maxResponseLogItems)
                {
                    responseTruncated = true;
                }

                var orderedItems = items.OrderBy(i => i.Timestamp).Take(maxResponseLogItems);

                var logResponse = new Api.LogResponse {
                    Items = new List <Api.LogItem>(), ResponseTruncated = responseTruncated
                };
                foreach (var item in orderedItems)
                {
                    if (!string.IsNullOrEmpty(item.SequenceId))
                    {
                        var sequenceItem = logResponse.Items.Where(i => i.Type == Api.LogItemTypes.Sequence && i.SequenceId == item.SequenceId).FirstOrDefault();
                        if (sequenceItem == null)
                        {
                            sequenceItem = new Api.LogItem
                            {
                                Timestamp  = item.Timestamp,
                                Type       = Api.LogItemTypes.Sequence,
                                SequenceId = item.SequenceId,
                                SubItems   = new List <Api.LogItem>()
                            };
                            logResponse.Items.Add(sequenceItem);
                        }
                        if (!string.IsNullOrEmpty(item.OperationId))
                        {
                            var operationItem = sequenceItem.SubItems.Where(i => i.Type == Api.LogItemTypes.Operation && i.OperationId == item.OperationId).FirstOrDefault();
                            if (operationItem == null)
                            {
                                operationItem = new Api.LogItem
                                {
                                    Timestamp   = item.Timestamp,
                                    Type        = Api.LogItemTypes.Operation,
                                    OperationId = item.OperationId,
                                    SubItems    = new List <Api.LogItem>(),
                                    Values      = new Dictionary <string, string>()
                                };
                                sequenceItem.SubItems.Add(operationItem);
                            }
                            HandleOperationName(item, operationItem);
                            HandleOperationTimestamp(item, operationItem);
                            operationItem.SubItems.Add(item);
                        }
                        else
                        {
                            HandleSequenceTimestamp(item, sequenceItem);
                            sequenceItem.SubItems.Add(item);
                        }
                    }
                    else if (!string.IsNullOrEmpty(item.OperationId))
                    {
                        var operationItem = logResponse.Items.Where(i => i.Type == Api.LogItemTypes.Operation && i.OperationId == item.OperationId).FirstOrDefault();
                        if (operationItem == null)
                        {
                            operationItem = new Api.LogItem
                            {
                                Timestamp   = item.Timestamp,
                                Type        = Api.LogItemTypes.Operation,
                                OperationId = item.OperationId,
                                SubItems    = new List <Api.LogItem>(),
                                Values      = new Dictionary <string, string>()
                            };
                            logResponse.Items.Add(operationItem);
                        }
                        HandleOperationName(item, operationItem);
                        HandleOperationTimestamp(item, operationItem);
                        operationItem.SubItems.Add(item);
                    }
                    else
                    {
                        logResponse.Items.Add(item);
                    }
                }

                return(Ok(logResponse));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 28
0
 public override void Run(CancellationToken cancellationToken)
 {
     LogsQueryClient.QueryWorkspace(TestEnvironment.WorkspaceId, LogsQuery, QueryTimeRange.All, cancellationToken: cancellationToken);
 }
Esempio n. 29
0
 public override async Task RunAsync(CancellationToken cancellationToken)
 {
     await LogsQueryClient.QueryWorkspaceAsync(TestEnvironment.WorkspaceId, LogsQuery, QueryTimeRange.All, cancellationToken : cancellationToken).ConfigureAwait(false);
 }