I have finally assembled an attempt to create a thread safe logging class and also ensured by file flags that file should not be accessed by different processes at same time. This classed will be inside DLL. Below is the implementation,
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();
}
}
}
Please note I am a beginner first of all, and if this class achieves the simple functionality of writing simple lines to file I am OK with it.
Of course you can comment also about other things which are in the context of CodeReview site. But please not too advanced feedback since as I said I am beginner.
Second, here are some specific questions I have about it:
Have I used the lock correctly?
This class maybe used by many threads, will I have performance problems because of thread waiting for each other? NOTE: I log only ERRORS so even if many threads are using it, not many errors should be occurring right? Also note how because of performance I have a cache for log messages.
Finally, only problem I see if different programs use this class to write to same file, how can I distinguish inside logs which program or process made an entry? How is this solved typically? (I assume one process can write to this file if another finished writing, isn't it?)
PS. This is all the functionality I want, I don't plan to extend this class. So please no recommendations about 3rd party libs. If my class achieves above points well, I am ok with it. Or if you see some problem with it, please tell.
And in general I am interested if its safe to use my class because some people always say to not create your own logging class. Is it ok if I use this class? I see people creating log classes such as here http://www.codeproject.com/Tips/585796/Simple-Log, so what is problem if I created one as above?