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);
            }
        }
        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 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
        }
        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
        }
        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 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 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 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 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());
        }
Example #11
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 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
        }
Example #14
0
 public override async Task RunAsync(CancellationToken cancellationToken)
 {
     await LogsQueryClient.QueryWorkspaceAsync(TestEnvironment.WorkspaceId, LogsQuery, QueryTimeRange.All, cancellationToken : cancellationToken).ConfigureAwait(false);
 }