2
0
Tranga/Logging/MemoryLogger.cs

74 lines
1.9 KiB
C#
Raw Permalink 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-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)
{
lock (_logMessages)
2023-09-02 21:53:09 +02:00
{
_logMessages.Add(DateTime.Now, value);
2023-09-02 21:53:09 +02:00
}
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++)
{
lock (_logMessages)
2023-09-02 21:53:09 +02:00
{
ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString();
}
}
_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
{
lock(_logMessages)
2023-09-02 21:53:09 +02:00
{
ret.Add(_logMessages.GetValueAtIndex(_lastLogMessageIndex + retIndex).ToString());
}
2023-09-01 22:41:06 +02:00
}
2023-10-04 18:14:46 +02:00
catch (NullReferenceException)//Called when LogMessage has not finished writing
2023-09-01 22:41:06 +02:00
{
break;
}
}
2023-09-01 22:41:06 +02:00
_lastLogMessageIndex = _lastLogMessageIndex + retIndex;
return ret.ToArray();
2023-05-20 21:47:54 +02:00
}
}