Skip to content

Commit

Permalink
Code Refactoring for LoggingService.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
aayushpandya committed Apr 2, 2023
1 parent 17f26a1 commit 622594c
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions src/Notepads/Services/LoggingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

public static class LoggingService
{
private const string MessageFormat = "{0} [{1}] {2}"; // {timestamp} [{level}] {message}
private const string MessageFormatString = "{0} [{1}] {2}"; // {timestamp} [{level}] {message}

private static readonly ConcurrentQueue<string> MessageQueue = new ConcurrentQueue<string>();
private static readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
Expand Down Expand Up @@ -69,7 +69,8 @@ public static void LogException(Exception ex, bool consoleOnly = false)

private static void LogMessage(string level, string message, bool consoleOnly)
{
string formattedMessage = string.Format(MessageFormat, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture), level, message);
string timeStamp = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
string formattedMessage = string.Format(MessageFormatString, timeStamp, level, message);

// Print to console
Debug.WriteLine(formattedMessage);
Expand Down Expand Up @@ -105,21 +106,7 @@ private static async Task<bool> InitializeLogFileWriterBackgroundTaskAsync()
DateTime.UtcNow.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture) + ".log");
}

_backgroundTask = Task.Run(
async () =>
{
while (true)
{
Thread.Sleep(LoggingInterval);

// We will try to write all pending messages in our next attempt, if the current attempt failed
// However, if the size of messages has become abnormally big, we know something is wrong and should abort at this point
if (!await TryFlushMessageQueueAsync() && Messages.Count > 1000)
{
break;
}
}
});
_backgroundTask = Task.Run(WriteLogMessages);

_initialized = true;
LogInfo($"Log file location: {_logFile.Path}", true);
Expand All @@ -136,6 +123,20 @@ private static async Task<bool> InitializeLogFileWriterBackgroundTaskAsync()

return false;
}
private static async Task WriteLogMessages()
{
while (true)
{
Thread.Sleep(LoggingInterval);

// We will try to write all pending messages in our next attempt, if the current attempt failed
// However, if the size of messages has become abnormally big, we know something is wrong and should abort at this point
if (!await TryFlushMessageQueueAsync() && Messages.Count > 1000)
{
break;
}
}
}

private static async Task<bool> TryFlushMessageQueueAsync()
{
Expand Down

0 comments on commit 622594c

Please sign in to comment.