2
0
Tranga/Logging/MemoryLogger.cs

82 lines
2.2 KiB
C#
Raw Normal View History

2023-05-20 21:47:54 +02:00
using System.Text;
namespace Logging;
public class MemoryLogger : LoggerBase
{
private readonly SortedList<DateTime, LogMessage> _logMessages = new();
private int _lastLogMessageIndex = 0;
2023-09-02 21:53:09 +02:00
private bool _lockLogMessages = false;
2023-05-20 21:47:54 +02:00
public MemoryLogger(Encoding? encoding = null) : base(encoding)
2023-05-20 21:47:54 +02:00
{
}
protected override void Write(LogMessage value)
{
2023-09-02 21:53:09 +02:00
if (!_lockLogMessages)
{
_lockLogMessages = true;
while(!_logMessages.TryAdd(DateTime.Now, value))
Thread.Sleep(10);
_lockLogMessages = false;
}
2023-05-20 21:47:54 +02:00
}
public string[] GetLogMessages()
2023-05-20 21:47:54 +02:00
{
return Tail(Convert.ToUInt32(_logMessages.Count));
2023-05-20 21:47:54 +02:00
}
public string[] Tail(uint? length)
2023-05-20 21:47:54 +02:00
{
int retLength;
if (length is null || length > _logMessages.Count)
retLength = _logMessages.Count;
else
retLength = (int)length;
string[] ret = new string[retLength];
2023-05-20 21:47:54 +02:00
for (int retIndex = 0; retIndex < ret.Length; retIndex++)
{
2023-09-02 21:53:09 +02:00
if (!_lockLogMessages)
{
_lockLogMessages = true;
ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString();
_lockLogMessages = false;
}
}
_lastLogMessageIndex = _logMessages.Count - 1;
return ret;
}
public string[] GetNewLines()
{
int logMessageCount = _logMessages.Count;
2023-09-01 22:41:06 +02:00
List<string> ret = new();
2023-09-01 22:41:06 +02:00
int retIndex = 0;
for (; retIndex < logMessageCount - _lastLogMessageIndex; retIndex++)
{
2023-09-01 22:41:06 +02:00
try
{
2023-09-02 21:53:09 +02:00
if (!_lockLogMessages)
{
_lockLogMessages = true;
ret.Add(_logMessages.GetValueAtIndex(_lastLogMessageIndex + retIndex).ToString());
_lockLogMessages = false;
}
2023-09-01 22:41:06 +02:00
}
catch (NullReferenceException e)//Called when LogMessage has not finished writing
{
break;
}
}
2023-09-01 22:41:06 +02:00
_lastLogMessageIndex = _lastLogMessageIndex + retIndex;
return ret.ToArray();
2023-05-20 21:47:54 +02:00
}
}