Merge branch 'bugfix/Logger' into develop

* bugfix/Logger:
  Fixed default logger behaviour on closing
This commit is contained in:
Serraniel 2018-04-06 00:08:03 +02:00
commit f6fbb203f8
2 changed files with 39 additions and 28 deletions

View file

@ -37,7 +37,7 @@ namespace SweetLib.Utils.Logger
/// <summary>
/// The default <see cref="ILogMemory"/> which will be used for any logging action, if no custom <see cref="ILogMemory"/> is set as parameter.
/// </summary>
public static ILogMemory DefaultLogMemory = new ArchivableConsoleLogMemory();
public static ILogMemory DefaultLogMemory { get; set; } = new ArchivableConsoleLogMemory();
/// <summary>
/// Will log a message into the global <see cref="DefaultLogMemory"/>.

View file

@ -8,7 +8,7 @@ using SweetLib.Utils.Logger.Message;
namespace SweetLib.Utils.Logger.Memory
{
public class ArchivableConsoleLogMemory : ILogMemory
public class ArchivableConsoleLogMemory : ILogMemory, IDisposable
{
private string TempFile { get; } = Path.GetTempFileName();
@ -26,40 +26,54 @@ namespace SweetLib.Utils.Logger.Memory
{
ArchiveFile = archiveFile;
QueueTimer = new Timer(e => ProcessQueue(), null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
QueueTimer = new Timer(e =>
{
if (Monitor.TryEnter(this))
{
try
{
ProcessQueue();
}
finally
{
Monitor.Exit(this);
}
}
}, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(500));
}
~ArchivableConsoleLogMemory()
{
Dispose(false);
Dispose(true);
GC.SuppressFinalize(this);
}
private void ProcessQueue(bool isDisposing = false)
private void ProcessQueue(bool disposing = false)
{
// quick exit
if (LogQueue.IsEmpty)
return;
// if we are disposing no need to lock. This might cause issues!
if (!isDisposing)
if (!disposing)
{
lock (this)
{
if (LogQueue.IsEmpty)
return;
while (!LogQueue.IsEmpty)
{
LogMessage message;
if (LogQueue.TryDequeue(out message))
File.AppendAllText(TempFile, message.ToString());
File.AppendAllText(TempFile, message.ToString() + Environment.NewLine);
}
}
}
else
{
if (LogQueue.IsEmpty)
return;
while (!LogQueue.IsEmpty)
{
LogMessage message;
if (LogQueue.TryDequeue(out message))
File.AppendAllText(TempFile, message.ToString());
File.AppendAllText(TempFile, message.ToString() + Environment.NewLine);
}
}
}
@ -95,8 +109,6 @@ namespace SweetLib.Utils.Logger.Memory
public void Forget(LogMessage message)
{
lock (this)
{
var lines = File.ReadAllLines(TempFile).ToList();
foreach (var line in lines)
@ -107,7 +119,6 @@ namespace SweetLib.Utils.Logger.Memory
File.WriteAllLines(TempFile, lines);
}
}
public void Archive(string fullFileName = null)
{