2023-05-20 21:47:54 +02:00
|
|
|
|
using System.Net.Mime;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace Logging;
|
|
|
|
|
|
|
|
|
|
public class Logger : TextWriter
|
|
|
|
|
{
|
|
|
|
|
public override Encoding Encoding { get; }
|
|
|
|
|
public enum LoggerType
|
|
|
|
|
{
|
|
|
|
|
FileLogger,
|
2023-05-21 02:10:32 +02:00
|
|
|
|
ConsoleLogger
|
2023-05-20 21:47:54 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private FileLogger? _fileLogger;
|
|
|
|
|
private FormattedConsoleLogger? _formattedConsoleLogger;
|
2023-05-21 02:10:32 +02:00
|
|
|
|
private MemoryLogger _memoryLogger;
|
2023-05-20 21:47:54 +02:00
|
|
|
|
private TextWriter? stdOut;
|
|
|
|
|
|
|
|
|
|
public Logger(LoggerType[] enabledLoggers, TextWriter? stdOut, Encoding? encoding, string? logFilePath)
|
|
|
|
|
{
|
|
|
|
|
this.Encoding = encoding ?? Encoding.ASCII;
|
|
|
|
|
this.stdOut = stdOut ?? null;
|
|
|
|
|
if (enabledLoggers.Contains(LoggerType.FileLogger) && logFilePath is not null)
|
|
|
|
|
_fileLogger = new FileLogger(logFilePath, null, encoding);
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
_fileLogger = null;
|
|
|
|
|
throw new ArgumentException($"logFilePath can not be null for LoggerType {LoggerType.FileLogger}");
|
|
|
|
|
}
|
|
|
|
|
_formattedConsoleLogger = enabledLoggers.Contains(LoggerType.ConsoleLogger) ? new FormattedConsoleLogger(null, encoding) : null;
|
2023-05-21 02:10:32 +02:00
|
|
|
|
_memoryLogger = new MemoryLogger(null, encoding);
|
2023-05-20 21:47:54 +02:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 22:10:24 +02:00
|
|
|
|
public void WriteLine(string caller, string? value)
|
2023-05-20 21:47:54 +02:00
|
|
|
|
{
|
|
|
|
|
value = value is null ? Environment.NewLine : string.Concat(value, Environment.NewLine);
|
|
|
|
|
|
|
|
|
|
Write(caller, value);
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 22:10:24 +02:00
|
|
|
|
public void Write(string caller, string? value)
|
2023-05-20 21:47:54 +02:00
|
|
|
|
{
|
|
|
|
|
if (value is null)
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
_fileLogger?.Write(caller, value);
|
|
|
|
|
_formattedConsoleLogger?.Write(caller, value);
|
|
|
|
|
|
2023-05-21 02:10:32 +02:00
|
|
|
|
_memoryLogger.Write(caller, value);
|
2023-05-20 21:47:54 +02:00
|
|
|
|
stdOut?.Write(value);
|
|
|
|
|
}
|
2023-05-21 02:10:32 +02:00
|
|
|
|
|
|
|
|
|
public string[] Tail(uint? lines)
|
|
|
|
|
{
|
|
|
|
|
return _memoryLogger.Tail(lines);
|
|
|
|
|
}
|
2023-05-20 21:47:54 +02:00
|
|
|
|
}
|