Log Analytics log search REST API for C#

I want to search Log Analytics Log via C#. However, we can't find a good sample on the internet.  You can find a good web page for log search REST API in /en-us/azure/log-analytics/log-analytics-log-search-api . However, the sample is only for ARMClient and Python. I wrote a simple sample using C#.

 

You can find whole source code on my Github.

Prerequisite

You need to prepare these things for the sample.

  • Clone my GitHub Repo
  • Log Analytics
  • Service Principle (Client ID, Client Secret, SubscriptionID, TenantID
  • Edit App.config

Then you are ready to understand the Code.

Authentication

Unfortunately, Log Analytics is not on the Azure SDK for C#. We need to implement the code by myself.  Data collector API and Log Search API is totally different authentication system. Log Search API is just Active Directory Access Token based Authentication. The implementation is not so difficult.

  public async Task<string> SearchAsync(string query)
 {
 // Authorization header for the Azure REST API
 var httpClient = new HttpClient();
 httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", await GetAccessToken());


               :

private async Task<string> GetAccessToken()
 {
 var authority = String.Format(CultureInfo.InvariantCulture, AuthenticationEndpoint, tenantId);
 var authContext = new AuthenticationContext(authority);
 var creadential = new ClientCredential(clientId, clientSecret);
 var result = await authContext.AcquireTokenAsync("https://management.core.windows.net/", creadential);
 return result.AccessToken;

}

 

The process is very simple. Using Service Principle, just request Access Token to the Azure Active Directory. Once you get the access token, you add it on the "Authorization: Bearer" header. If the Access Token expired, you need to refresh it. However, I'm not included the refreshment this time for the simplicity.

Send HttpRequest

Then request it.  It might be not difficult.

               :

 // Content with Content-Type
 var content = new StringContent(GetQueryString(query), Encoding.UTF8, "application/json");
 // Execute
 var response = await httpClient.PostAsync(GetUri(), content);
               :
 private string GetUri()
 {
 return $"{AzureURIBase}/subscriptions/{this.subscriptionId}/resourceGroups/{this.resourceGroup}/providers/Microsoft.OperationalInsights/workspaces/{this.workspaceName}/search?api-version=2015-03-20";
 }

 

Filter Log

I have one tip for the search.  If you query it via "*", you will get a lot of logs. It includes what you don't want.  In this case, I include log type. It helps you to distinguish the log. e.g. I want to fetch the log which I wrote from my Azure Functions. I specify the recordType as "CQRTelemetry".  This query fetch only my log which I wrote by my self.

 

 string result = await SearchAsync("Type=CQRTelemetry_CL");

 

Deserialize

Deserialize from Json to a class is boring task. However, Visual Studio 2017 might help you to do it. Now we can copy the json, then "Paste Special > Paste JSON As Class" it. Then you can find the classes for JSON deserialize. It is handy!

  ->  

I did it, you can find the class which I pasted it on the Model.cs file.

Just deserialize it.

  // Deserialize the Json into Model objects
 var resultObject = JsonConvert.DeserializeObject<Rootobject>(await response.Content.ReadAsStringAsync());

 

You need to specify Rootobject which is the RootObject of the JSON. This is auto generated by Visual Studio 2017. If you don't like the name, you can rename it.

 

Error Handling

Sometimes, the query will be an error. How can we find it?  The API includes __metadata.resultType. Once we've got query error, it will be "error".

  // Error Handling
 if (resultObject.__metadata.resultType == "error")
 {
 throw new Exception("Search Result Error!");
 }

Conclusion

That's it! Now you can enjoy coding for the Log Analytics Search API on C#.  I don't know why however, the Azure SDK doesn't support Log Analytics Search API. The SDK is very convenient, so we should not care about the detail. However, if you want to write code for REST-API, you need to understand the behavior and spec. Now you ready to enjoy!

Resource