Archiving Logs in Azure Blob Storage from Azure log Tables

Azure provides Pay as you go service, so it is important to use the services efficiently. Pricing of table storage is higher than blob storage, so it is good idea to archive your logs to the blob storage. Diagnostic enabled for Azure cloud service configuration.

We and retrieve record from both the tables ( WadLogsTable, WADWindowsEventLogTable).        

  1. /// <summary>  
  2. /// Retrives Log data from Azure storage table  
  3. /// </summary>  
  4. /// <typeparam name="T">Table type for which we will retrive record</typeparam>  
  5. /// <param name="environment">Environment (UAT,PROD). </param>  
  6. /// <param name="startTick">starting/ from tick</param>  
  7. /// <param name="endTick">ending/ to Tick</param>  
  8. /// <returns></returns>  
  9.    
  10. private List<T> GetLogFromTable<T>(string environment, long startTick, long endTick)  
  11. where T : TableEntity, new()  
  12. {  
  13.             //Initializing storage Account with the proper storage connection string  
  14.             CloudStorageAccount storageAccount =             CloudStorageAccount.Parse(ConfigurationManager.AppSettings[environment].ToString());  
  15.    
  16.             // Create the table client.  
  17.             CloudTableClient tableClient = storageAccount.CreateCloudTableClient();  
  18.    
  19.             //Get the referance of the storage table   
  20.             CloudTable table = tableClient.GetTableReference(typeof(T).Name);  
  21.    
  22.             //Checks If table exists  
  23.             if (table.Exists())  
  24.             {  
  25.                      //Partition key in the log table are date time tick  
  26.                      //Creating Query Partition key between start and end ticks  
  27.                      TableQuery<T> q = new TableQuery<T>().Where(  
  28.                      TableQuery.CombineFilters(  
  29.                             TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, "0" + startTick),  
  30.                             TableOperators.And,  
  31.                              TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.LessThan, "0" + end Tick)));  
  32.                     
  33.                      //Retriving Records from storage table  
  34.                      return table.ExecuteQuery<T>(q).ToList<T>();  
  35.             }  
  36.          return null;  
  37. }  
  38.    
  39.    
  40. /// <summary>  
  41. /// Appends the data in text file and convert it to bytes  
  42. /// </summary>  
  43. /// <typeparam name="T">Table type for which is retrive record</typeparam>  
  44. /// <param name="list">Log data retrived from table storage</param>  
  45. /// <param name="fileName">name of the file</param>  
  46. /// <returns>bytes of file</returns>  
  47.    
  48. private byte[] ConvertTableToBytes<T>( IList<T> list, string fileName)  
  49. where T : TableEntity, new()  
  50. {  
  51.             // Instances which will help in creating the content of file  
  52.             StringBuilder headerText = new StringBuilder();  
  53.             StringBuilder contentText = new StringBuilder();  
  54.             List<PropertyInfo> listOfProperties = new List<PropertyInfo>();  
  55.             string delemiter = "\t";  
  56.             string filetype = "txt";  
  57.            
  58.             //Retriving the list of property  
  59.             foreach (var prop in typeof(T).GetProperties())  
  60.             {  
  61.                      listOfProperties.Add(prop);  
  62.                      headerText.AppendFormat("{0}{1}", prop.Name, delemiter);  
  63.             }  
  64.               
  65.             StringBuilder logText = new StringBuilder();  
  66.               
  67.             //Appending header text  
  68.             logText.AppendLine(headerText.ToString());  
  69.    
  70.             //Appending data from each item  
  71.             foreach (T item in list)  
  72.             {  
  73.                         contentText.Clear();  
  74.                         foreach (var prop in listOfProperties)  
  75.                         {  
  76.                                  contentText.AppendFormat("{0}{1}", prop.GetValue(item), delemiter);  
  77.                         }  
  78.                         logText.AppendLine(contentText.ToString());  
  79.          }  
  80.    
  81.             //Storing file in temp location and converting it in bytes  
  82.             File.WriteAllText("_" + fileName + "." + filetype, logText.ToString(), Encoding.Unicode);  
  83.             byte[] result = File.ReadAllBytes("_" + fileName + "." + filetype);  
  84.       return result;  
  85. }  
  86.    
  87. /// <summary>  
  88. /// Upload the bytes of data to blob storage  
  89. /// </summary>  
  90. /// <param name="environment">Environment (UAT,PROD). </param>  
  91. /// <param name="Container">Name of container in which files will be archive</param>  
  92. /// <param name="fileName">Name of file</param>  
  93. /// <param name="file">Data of file in byte format</param>  
  94. /// <returns></returns>  
  95.    
  96. private string UploadToBlob(string environment, string Container, string fileName, byte[] file)  
  97. {  
  98.             //Initializing storage Account with the proper storage connection string  
  99.             CloudStorageAccount storageAccount =             CloudStorageAccount.Parse(ConfigurationManager.AppSettings[environment].ToString());  
  100.               
  101.             // Create the blob client.  
  102.             CloudBlobClient blogClient = storageAccount.CreateCloudBlobClient();  
  103.    
  104.             //Referencing Container  
  105.             CloudBlobContainer container = blogClient.GetContainerReference(Container.ToLower());  
  106.    
  107.             //If container not exist it will create a new container with specified name  
  108.             container.CreateIfNotExists();  
  109.    
  110.             //referance file name inside container  
  111.             CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);  
  112.    
  113.             //Create a stream and uploading the data in blob storage  
  114.             using (var memoryStream = new System.IO.MemoryStream(file))  
  115.             {  
  116.                         blockBlob.UploadFromStream(memoryStream);  
  117.             }  
  118.    
  119.             //URL in which file is uploaded  
  120.       return blockBlob.Uri.ToString();  
  121. }  
  122.    
  123. /// <summary>  
  124. /// Delete the records from the logs table  
  125. /// </summary>  
  126. /// <typeparam name="T">Table type for which is retrive record</typeparam>  
  127. /// <param name="environment">Environment (UAT,PROD). Code will retrive connection string depend on environment </param>  
  128. /// <param name="startTick">starting/ from tick</param>  
  129. /// <param name="endTick">ending/ to Tick</param>  
  130. /// <param name="list">Log data retrived from table storage</param>  
  131. /// <returns>returns success or failure</returns>  
  132.    
  133. private bool DeleteBulkDataFromAzureTable<T>(string environment, long startTick, long endTick, IList<T> list)  
  134. where T : TableEntity, new()  
  135. {  
  136.             //Initializing storage Account with the proper storage connection string  
  137.             CloudStorageAccount storageAccount =             CloudStorageAccount.Parse(ConfigurationManager.AppSettings[environment].ToString());  
  138.               
  139.             // Create the table client.  
  140.             CloudTableClient tableClient = storageAccount.CreateCloudTableClient();  
  141.    
  142.             //Referencing table  
  143.             CloudTable table = tableClient.GetTableReference(typeof(T).Name);  
  144.      
  145.             //Checks if table exists  
  146.             if (table.Exists())  
  147.             {  
  148.                         //Loop through each item and delete from the log table  
  149.                         foreach (var item in list)  
  150.                         {  
  151.    
  152.                               // Create the Delete TableOperation.  
  153.                               if (item != null)  
  154.                               {  
  155.                                     TableOperation deleteOperation = TableOperation.Delete(item);  
  156.                                 
  157.                                        // Execute the operation.  
  158.                                     table.Execute(deleteOperation);  
  159.                               }  
  160.                         }  
  161.                   return true;  
  162.             }  
  163.       return false;  
  164. }