Accessing data from Log Analytics using C#

Step 1: Register an app in active directory app registration

You need to do a new application registration

Once that application is registered you need the application Id which is also called the client id. The other thing that you need to configure the permission.

In permission you need to give access to log analytics data as user that should be given

Step2: then we should have a secret id from the azure

That you can get from the key configure that in the app that you just register and make a new key you need o save that

Once you have that lets switch to log analytics

Step3: you need to the workspace id from the log analytics

Step4: to access control

Add a new role assignment

Role: Contributor

Select: the app that you created

Save

Now you have set the framework and the two way communication between the app and log analytics. Now comes the code part so we need the following code

public async void GetMetricBeat()
        {
            var token = await GetAccessToken();
            var workspaceId = "workspace id";
            var query = JsonConvert.SerializeObject(new
            {
                query = " metricbeat_CL | take 10"
            });
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
 
                var postContent = new StringContent(query, Encoding.UTF8, "application/json");
                var response = await client.PostAsync($"https://api.loganalytics.io/v1/workspaces/{workspaceId}/query", postContent);
 
                HttpContent responseContent = response.Content;
                //returning a string based Json
                var content = await response.Content.ReadAsStringAsync();
               
                              
                Console.WriteLine(content);
 
            }
 
            Console.ReadKey();
        }
 
        private async Task<string> GetAccessToken()
        {
            var authority = String.Format(CultureInfo.InvariantCulture, "https://login.windows.net/{0}", TenantId);
 
 
            var authContext = new AuthenticationContext(authority);
            var creadential = new ClientCredential(ClientId, ClientSecret);
            var result = await authContext.AcquireTokenAsync("https://api.loganalytics.io/", creadential);
            return result.AccessToken;
 
        }

Lets walkthrough the code a bit.

So the first thing that we do in GetMetricBeat is to get the access token. Before we move forward we can see how that is made. So to get the token we are contracting the URL. To access the long analytics the URL is  ‘https://login.windows.net/’tenantID. Once that is constructed we need to create the client credential for the app that that we have created by providing the clientappID and clientAppSecret to acquire the access token.

After that we are constructing a very basic log analytics query which is in Json format.

To access the log we have to create a HTTP request to ‘https://api.loganalytics.io/v1/workspaces/{workspaceId}/query’ by providing the workspace if. The http client must be given the access token for a valid request. Once we post the request a json will be returned as a return string value that we can parse for our result.