Send data to Azure Log Analytics from C# code

Sending data to Azure Log Analytics from your C# code

Azure as a part of Microsoft Operations Management Suite provides data collection and insight services inside Azure cloud platform.

It allows you to:

If your cloud infrastructure is in Azure then this might be your choice for collecting and analyzing logs from your application. It supports out of the box text file logs collection and aggregation which can be further analyzed. 

If you do not want to deal with flat files and want to push your data directly to Azure Log Analytics from your code, you can do this by using Azure REST API.

Before you start writing code, you first need to create a Workspace in Azure Log Analytics which will be container of your data collected. Azure provides free 500MB for stored data with one moth retention for free, so if you do not need more than this you can keep your workspace in a free tier.

After creating a Workspace, you are going to need get a WORKSPACE ID and PRIMARY KEY which you will use in Azure REST API call.

Log Analytics Keys

Once you have the WORKSPACE ID and PRIMARY KEY you can start writing code for pushing your data to Azure Log Analytics. This is a sample class that is doing authentication to Azure REST API endpoint and posting the data you want to save in your Log Analytics workspace.

public class AzureLogAnalytics
{
public String WorkspaceId { get; set; }
public String SharedKey { get; set; }
public String ApiVersion { get; set; }
public String LogType { get; set; }
public AzureLogAnalytics(String workspaceId, String sharedKey, String logType, String apiVersion = "2016-04-01")
{
this.WorkspaceId = workspaceId;
this.SharedKey = sharedKey;
this.LogType = logType;
this.ApiVersion = apiVersion;
}
public void Post(string json)
{
string requestUriString = $"https://{WorkspaceId}.ods.opinsights.azure.com/api/logs?api-version={ApiVersion}";
DateTime dateTime = DateTime.UtcNow;
string dateString = dateTime.ToString("r");
string signature = GetSignature("POST", json.Length, "application/json", dateString, "/api/logs");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
request.ContentType = "application/json";
request.Method = "POST";
request.Headers["Log-Type"] = LogType;
request.Headers["x-ms-date"] = dateString;
request.Headers["Authorization"] = signature;
byte[] content = Encoding.UTF8.GetBytes(json);
using (Stream requestStreamAsync = request.GetRequestStream())
{
requestStreamAsync.Write(content, 0, content.Length);
}
using (HttpWebResponse responseAsync = (HttpWebResponse)request.GetResponse())
{
if (responseAsync.StatusCode != HttpStatusCode.OK && responseAsync.StatusCode != HttpStatusCode.Accepted)
                {
                    Stream responseStream = responseAsync.GetResponseStream();
                    if (responseStream != null)
                    {
                        using (StreamReader streamReader = new StreamReader(responseStream))
                        {
                            throw new Exception(streamReader.ReadToEnd());
                        }
                    }
                }
            }
        }

        private string GetSignature(string method, int contentLength, string contentType, string date, string resource)
        {
            string message = $"{method}
{contentLength}
{contentType}
x-ms-date:{date}
{resource}";
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            using (HMACSHA256 encryptor = new HMACSHA256(Convert.FromBase64String(SharedKey)))
            {
                return $"SharedKey {WorkspaceId}:{Convert.ToBase64String(encryptor.ComputeHash(bytes))}";
            }
        }

    }
    

Now to send the data using the AzureLogAnalytics class 

            AzureLogAnalytics logAnalytics = new AzureLogAnalytics(
                workspaceId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeee",
                sharedKey: "Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123Abc123A==",
                logType: "ApplicationLog");

            logAnalytics.Post(JsonConvert.SerializeObject(
                new
                {
                    id = Guid.NewGuid().ToString(),
                    datetime = DateTime.Now,
                    message = "Hello from test app"
                }));
    

After run, log type ApplicationLog_CL will show up in the Log Analytics Azure UI (suffix _CL is added automatically by azure and it stands for Custom Log). 

Note

The data and log type may not appear right away as Azure is not indexing at runtime, so you might expect your data to show up in about 1-5 minutes

ApplicationLog_CL
| order by TimeGenerated desc 
    

Log Analytics Record

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article