Coding, Windows 8

Simple file based exception logger for windows 8 app

Proper exception handling is the key factor to any good application development. But what if we want to log the exception details or additional information to a log file which users can send us for review.

If you really want to pin point what exactly went wrong after an application crash you should have a exception logger of some sort. So this will cover how to write you own exception logger for a windows 8 application. For me it was a life save and i am sure it will be helpful for my readers too.

The main method to call will be LogException which will log the exception. The other method’s in this article are helper methods which are mainly refactored to keep the code cleaner (inspired by Clean Coder & Clean Code, both are awesome and must read books for any developer)

Usage:

        catch (Exception ex)
        {
            ExceptionLogger.LogException(ex);
        }
       public static void LogException(Exception currentException)
       {
           String exceptionMessage = CreateErrorMessage(currentException);
           PurgeLogFiles();
           LogFileWrite(exceptionMessage);
       }

The CreateErrorMessage method prepares the exception message using the exception object passed. You can sanitize this method as per your need.

       /// 
       /// This method is for prepare the error message to log using Exception object
       /// 
       /// 
       /// 
       private static String CreateErrorMessage(Exception currentException)
       {
           StringBuilder messageBuilder = new StringBuilder();
           try
           {
               messageBuilder.AppendLine("-----------------------------------------------------------------");
               messageBuilder.AppendLine("Source: " + currentException.Source.ToString().Trim());
               messageBuilder.AppendLine("Date Time: " + DateTime.Now);
               messageBuilder.AppendLine("-----------------------------------------------------------------");
               messageBuilder.AppendLine("Method: " + currentException.Message.ToString().Trim());
               messageBuilder.AppendLine("Exception :: " + currentException.ToString());
               if (currentException.InnerException != null)
               {
                   messageBuilder.AppendLine("InnerException :: " + currentException.InnerException.ToString());
               }
               messageBuilder.AppendLine("");
               return messageBuilder.ToString();
           }
           catch
           {
               messageBuilder.AppendLine("Exception:: Unknown Exception.");
               return messageBuilder.ToString();
           } 
       }

The LogFileWrite method does the actual write operation based on a unique date based file that is created. It only generates one log file per day only if an exception occurs a given day.

       /// 
       /// This method is for writing the Log file with the current exception message
       /// 
       /// 
       private static async void LogFileWrite(string exceptionMessage)
       {
           try
           {
               string fileName = "BP-Log" + "-" + DateTime.Today.ToString("yyyyMMdd") + "." + "log";
               var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
               var logFolder = await localFolder.CreateFolderAsync("Logs", Windows.Storage.CreationCollisionOption.OpenIfExists);
               var logFile = await logFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.OpenIfExists);

               if (!String.IsNullOrEmpty(exceptionMessage))
               {
                   await FileIO.AppendTextAsync(logFile, exceptionMessage);                   
               } 
           }
           catch (Exception)
           {
               throw;
           } 
       }

The PurgeLogFiles method performs the housekeeping task by purging the older files so free up space. You can configure the daysToKeepLog variable to set the latest x number of days of log files you want to keep.

       ///  
       /// This method purge old log files in the log folder, which are older than daysToKeepLog. 
       /// 
       ///  
       ///  
       public static async void PurgeLogFiles()
       {
           int daysToKeepLog;
           DateTime todaysDate;
           var logFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

           try
           {
               daysToKeepLog = 5;
               todaysDate = DateTime.Now.Date;

               logFolder = await logFolder.GetFolderAsync("Logs");
               IReadOnlyList files = await logFolder.GetFilesAsync();

               foreach (StorageFile file in files)
               {
                   BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
                   if (file.FileType == ".log")
                   {
                       if (DateTime.Compare(todaysDate, basicProperties.DateModified.AddDays(daysToKeepLog).DateTime.Date) >= 0)
                       {
                           await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                       }
                   }
               }
           }
           catch (Exception)
           {
               throw;

           }

You can download the source file here Windows 8 Exception Logger

If you enjoyed this post, please consider sharing, leaving a comment, or subscribing to the RSS feed to have future articles delivered to your feed reader.