Skip to content

Commit

Permalink
Refactor classes and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sfc-gh-ext-simba-lf committed Dec 3, 2024
1 parent c1b8d5a commit 2fe82b1
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 123 deletions.
12 changes: 7 additions & 5 deletions Snowflake.Data.Tests/UnitTests/Logger/EasyLoggerManagerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,20 +125,22 @@ public void TestThatLogsToProperFileWithProperLogLevelOnly()
Assert.That(logLines, Has.Exactly(1).Matches<string>(s => s.Contains(FatalMessage)));

// arrange
File.Delete(FindLogFilePath(t_directoryLogPath));
EasyLoggerManager.Instance.ReconfigureEasyLogging(EasyLoggingLogLevel.Debug, t_directoryLogPath);

// act
logger.Debug(DebugMessage);

// assert
logLines = File.ReadLines(FindLogFilePath(t_directoryLogPath, 2));
logLines = File.ReadLines(FindLogFilePath(t_directoryLogPath));
Assert.That(logLines, Has.Exactly(1).Matches<string>(s => s.Contains(DebugMessage)));
}

[Test]
public void TestThatRollsLogIfSizeIsTooBig()
{
// arrange
const int expecetedBackupLogCount = 2;
var logger = SFLoggerFactory.GetSFLogger<SFBlockingChunkDownloaderV3>();
EasyLoggerManager.Instance.ReconfigureEasyLogging(EasyLoggingLogLevel.Trace, t_directoryLogPath);

Expand All @@ -151,7 +153,7 @@ public void TestThatRollsLogIfSizeIsTooBig()
_name = "RollingFileAppender",
_logFilePath = Path.Combine(t_directoryLogPath, logFileName),
_maximumFileSize = 1,
_maxSizeRollBackups = 2,
_maxSizeRollBackups = expecetedBackupLogCount,
_patternLayout = EasyLoggerManager.PatternLayout()
});

Expand All @@ -164,7 +166,7 @@ public void TestThatRollsLogIfSizeIsTooBig()
var backupLogs = Directory.GetFiles(t_directoryLogPath, $"{logFileName}.*.bak");

// assert
Assert.AreEqual(2, backupLogs.Length);
Assert.AreEqual(expecetedBackupLogCount, backupLogs.Length);
}

[Test]
Expand Down Expand Up @@ -205,11 +207,11 @@ private static string RandomLogsDirectoryPath()
return Path.Combine(s_logsDirectory, $"easy_logging_logs_{randomName}", "dotnet");
}

private static string FindLogFilePath(string directoryLogPath, int expectedFileCount = 1)
private static string FindLogFilePath(string directoryLogPath)
{
Assert.IsTrue(Directory.Exists(directoryLogPath));
var files = Directory.GetFiles(directoryLogPath);
Assert.AreEqual(expectedFileCount, files.Length);
Assert.AreEqual(1, files.Length);
return files.First();
}

Expand Down
13 changes: 13 additions & 0 deletions Snowflake.Data/Logger/SFAppender.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
//* Copyright (c) 2024 Snowflake Computing Inc. All rights reserved.
*/

using System;

namespace Snowflake.Data.Log
{
public interface SFAppender
{
void Append(string logLevel, string message, Type type, Exception ex = null);
}
}
119 changes: 119 additions & 0 deletions Snowflake.Data/Logger/SFAppenderImpl.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* Copyright (c) 2024 Snowflake Computing Inc. All rights reserved.
*/

using Snowflake.Data.Log;
using System;
using System.IO;
using System.Linq;
using System.Threading;

internal class PatternLayout
{
internal string _conversionPattern;

public PatternLayout() { }

public string Format(string logLevel, string message, Type type)
{
var formattedMessage = _conversionPattern
.Replace("%date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
.Replace("%t", Thread.CurrentThread.ManagedThreadId.ToString())
.Replace("%-5level", logLevel)
.Replace("%logger", type.ToString())
.Replace("%message", message)
.Replace("%newline", "\n");

return formattedMessage;
}
}

internal class SFConsoleAppender : SFAppender
{
internal string _name;
internal PatternLayout _patternLayout;

public SFConsoleAppender() { }

public void Append(string logLevel, string message, Type type, Exception ex = null)
{
var formattedMessage = _patternLayout.Format(logLevel, message, type);
Console.Write(formattedMessage);
if (ex != null)
{
Console.WriteLine(ex.Message);
}
}
}

internal class SFRollingFileAppender : SFAppender
{
internal string _name;
internal string _logFilePath;
internal long _maximumFileSize;
internal int _maxSizeRollBackups;
internal PatternLayout _patternLayout;

public SFRollingFileAppender() { }

public void Append(string logLevel, string message, Type type, Exception ex = null)
{
try
{
if (FileIsTooLarge())
{
RollFile();
}

var formattedMessage = _patternLayout.Format(logLevel, message, type);
using (var writer = new StreamWriter(_logFilePath, true))
{
writer.Write(formattedMessage);
if (ex != null)
{
writer.WriteLine(ex.Message);
}
}
}
catch (Exception logEx)
{
Console.WriteLine($"Failed to log message: {logEx.Message}");
}
}

public void ActivateOptions()
{
var logDir = Path.GetDirectoryName(_logFilePath);
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
if (!File.Exists(_logFilePath))
{
var file = File.Create(_logFilePath);
file.Close();
}
}

private bool FileIsTooLarge()
{
FileInfo fileInfo = new FileInfo(_logFilePath);
return fileInfo.Exists && fileInfo.Length > _maximumFileSize;
}

private void RollFile()
{
string rollFilePath = $"{_logFilePath}.{DateTime.Now:yyyyMMddHHmmss}.bak";
File.Move(_logFilePath, rollFilePath);

var logDirectory = Path.GetDirectoryName(_logFilePath);
var logFileName = Path.GetFileName(_logFilePath);
var rollFiles = Directory.GetFiles(logDirectory, $"{logFileName}.*.bak")
.OrderByDescending(f => f)
.Skip(_maxSizeRollBackups);
foreach (var oldRollFile in rollFiles)
{
File.Delete(oldRollFile);
}
}
}
5 changes: 0 additions & 5 deletions Snowflake.Data/Logger/SFLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,4 @@ public enum LoggingEvent
{
OFF, TRACE, DEBUG, INFO, WARN, ERROR, FATAL
}

public interface SFAppender
{
void Append(string logLevel, string message, Type type, Exception ex = null);
}
}
113 changes: 0 additions & 113 deletions Snowflake.Data/Logger/SFLoggerImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
using Snowflake.Data.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;

public static class SFLogRepository
{
Expand All @@ -19,116 +16,6 @@ internal static SFLogger GetRootLogger()
}
}

internal class PatternLayout
{
internal string _conversionPattern;

public PatternLayout() { }

public string Format(string logLevel, string message, Type type)
{
var formattedMessage = _conversionPattern
.Replace("%date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
.Replace("%t", Thread.CurrentThread.ManagedThreadId.ToString())
.Replace("%-5level", logLevel)
.Replace("%logger", type.ToString())
.Replace("%message", message)
.Replace("%newline", "\n");

return formattedMessage;
}
}

internal class SFConsoleAppender : SFAppender
{
internal string _name;
internal PatternLayout _patternLayout;

public SFConsoleAppender() { }

public void Append(string logLevel, string message, Type type, Exception ex = null)
{
var formattedMessage = _patternLayout.Format(logLevel, message, type);
Console.Write(formattedMessage);
if (ex != null)
{
Console.WriteLine(ex.Message);
}
}
}

internal class SFRollingFileAppender : SFAppender
{
internal string _name;
internal string _logFilePath;
internal long _maximumFileSize;
internal int _maxSizeRollBackups;
internal PatternLayout _patternLayout;

public SFRollingFileAppender() { }

public void Append(string logLevel, string message, Type type, Exception ex = null)
{
try
{
if (FileIsTooLarge())
{
RollFile();
}

var formattedMessage = _patternLayout.Format(logLevel, message, type);
using (var writer = new StreamWriter(_logFilePath, true))
{
writer.Write(formattedMessage);
if (ex != null)
{
writer.WriteLine(ex.Message);
}
}
}
catch (Exception logEx)
{
Console.WriteLine($"Failed to log message: {logEx.Message}");
}
}

public void ActivateOptions()
{
var logDir = Path.GetDirectoryName(_logFilePath);
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
if (!File.Exists(_logFilePath))
{
var file = File.Create(_logFilePath);
file.Close();
}
}

private bool FileIsTooLarge()
{
FileInfo fileInfo = new FileInfo(_logFilePath);
return fileInfo.Exists && fileInfo.Length > _maximumFileSize;
}

private void RollFile()
{
string rollFilePath = $"{_logFilePath}.{DateTime.Now:yyyyMMddHHmmss}.bak";
File.Move(_logFilePath, rollFilePath);

var logDirectory = Path.GetDirectoryName(_logFilePath);
var logFileName = Path.GetFileName(_logFilePath);
var rollFiles = Directory.GetFiles(logDirectory, $"{logFileName}.*.bak")
.OrderByDescending(f => f)
.Skip(_maxSizeRollBackups);
foreach (var oldRollFile in rollFiles)
{
File.Delete(oldRollFile);
}
}
}

public class SFLoggerImpl : SFLogger
{
private readonly Type _type;
Expand Down

0 comments on commit 2fe82b1

Please sign in to comment.