static class GMLogger
{
private static List<string> _buffer = new List<string>();
private static int _maxBufferSize = 25; // number of messages permitted in the buffer at a time
public static string _logDir = "C:\\Logs";
private static readonly object _syncObject = new object();
// Log message
public static void Log(string logMessage)
{
try
{
lock (_syncObject)
{
_buffer.Add(logMessage);
Save(_buffer);
}
}
catch (Exception ex)
{
throw;
}
}
// Save buffer if needed
private static void Save(List<string> buffer)
{
if (buffer.Count > _maxBufferSize)
{
// Write to file
if (!_logDir.EndsWith("\\")) _logDir += "\\";
DirectoryInfo di = Directory.CreateDirectory(_logDir);
var todaysLogFilePath = Path.Combine(_logDir,
("Log" + DateTime.Now.ToString("yyyy-MMMM-dd") + ".txt"));
using (FileStream aFile = new FileStream(todaysLogFilePath, FileMode.Append, FileAccess.Write, FileShare.None))
using (StreamWriter sw = new StreamWriter(aFile))
{
for (int i = 0; i < buffer.Count(); i++)
{
sw.WriteLine(buffer[i]);
}
}
// Clear buffer
buffer.Clear();
}
}
}