ln.logging/ln.logging/MemoryLogger.cs

111 lines
3.3 KiB
C#

// /**
// * File: MemoryLogger.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using ln.logging;
using System.Linq;
namespace ln.logging
{
public class MemoryLogger : ILoggingBackend
{
private LogEntry[] Entries = new LogEntry[256];
private int CurrentLogPointer = 255;
public MemoryLogger()
{
}
public MemoryLogger(int bufferLength)
{
Entries = new LogEntry[bufferLength];
CurrentLogPointer = Entries.Length - 1;
}
public LogLevel MinLogLevel { get; set; } = LogLevel.FATAL;
public LogLevel MaxLogLevel { get; set; } = LogLevel.INFO;
public void Message(LogLevel logLevel, string[] lines)
{
lock (this)
{
Entries[CurrentLogPointer].LogLevel = logLevel;
Entries[CurrentLogPointer].Lines = String.Join("\n", lines);
CurrentLogPointer = NextLogPointer;
}
}
public LogEntry[] GetLogEntries()
{
lock (this)
{
LogEntry[] prepare = new LogEntry[Entries.Length];
if (CurrentLogPointer == (Entries.Length - 1))
{
Array.Copy(Entries, prepare, Entries.Length);
}
else
{
Array.Copy(Entries, PreviousLogPointer, prepare, 0, Entries.Length - PreviousLogPointer);
Array.Copy(Entries, 0, prepare, Entries.Length - PreviousLogPointer, PreviousLogPointer);
}
return prepare.Where((x) => x.Lines != null).ToArray();
}
}
public LogEntry[] GetLogEntries(LogLevel maxLogLevel)
{
lock (this)
{
LogEntry[] prepare = new LogEntry[Entries.Length];
if (CurrentLogPointer == (Entries.Length - 1))
{
Array.Copy(Entries, prepare, Entries.Length);
}
else
{
Array.Copy(Entries, PreviousLogPointer, prepare, 0, Entries.Length - PreviousLogPointer);
Array.Copy(Entries, 0, prepare, Entries.Length - PreviousLogPointer, PreviousLogPointer);
}
return prepare.Where((x) => (x.Lines != null) && (maxLogLevel >= x.LogLevel)).ToArray();
}
}
private int NextLogPointer
{
get
{
int current = CurrentLogPointer;
current--;
if (current < 0)
current = Entries.Length - 1;
return current;
}
}
private int PreviousLogPointer
{
get
{
int current = CurrentLogPointer;
current++;
if (current >= Entries.Length)
current = 0;
return current;
}
}
public struct LogEntry
{
public LogLevel LogLevel;
public string Lines;
}
}
}