2
0
Tranga/Logging/Logger.cs

80 lines
2.7 KiB
C#
Raw Normal View History

using System.Runtime.InteropServices;
using System.Text;
2023-05-20 21:47:54 +02:00
namespace Logging;
public class Logger : TextWriter
{
private static readonly string LogDirectoryPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? "/var/log/tranga-api"
: Path.Join(Directory.GetCurrentDirectory(), "logs");
public string? logFilePath => _fileLogger?.logFilePath;
2023-05-20 21:47:54 +02:00
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 readonly FileLogger? _fileLogger;
private readonly FormattedConsoleLogger? _formattedConsoleLogger;
private readonly MemoryLogger _memoryLogger;
2023-05-20 21:47:54 +02:00
public Logger(LoggerType[] enabledLoggers, TextWriter? stdOut, Encoding? encoding, string? logFolderPath)
2023-05-20 21:47:54 +02:00
{
this.Encoding = encoding ?? Encoding.UTF8;
DateTime now = DateTime.Now;
if(enabledLoggers.Contains(LoggerType.FileLogger) && (logFolderPath is null || logFolderPath == ""))
2023-05-20 21:47:54 +02:00
{
string filePath = Path.Join(LogDirectoryPath,
2023-09-08 19:28:44 +02:00
$"{now.ToShortDateString()}_{now.Hour}-{now.Minute}-{now.Second}.log");
_fileLogger = new FileLogger(filePath, encoding);
}else if (enabledLoggers.Contains(LoggerType.FileLogger) && logFolderPath is not null)
_fileLogger = new FileLogger(Path.Join(logFolderPath, $"{now.ToShortDateString()}_{now.Hour}-{now.Minute}-{now.Second}.log") , encoding);
2023-09-08 19:28:44 +02:00
if (enabledLoggers.Contains(LoggerType.ConsoleLogger) && stdOut is not null)
{
_formattedConsoleLogger = new FormattedConsoleLogger(stdOut, encoding);
}
2023-07-31 00:31:19 +02:00
else if (enabledLoggers.Contains(LoggerType.ConsoleLogger) && stdOut is null)
{
_formattedConsoleLogger = null;
throw new ArgumentException($"stdOut can not be null for LoggerType {LoggerType.ConsoleLogger}");
}
_memoryLogger = new MemoryLogger(encoding);
WriteLine(GetType().ToString(), $"Logfile: {logFilePath}");
2023-05-20 21:47:54 +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);
}
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
}
2023-05-21 02:10:32 +02:00
public string[] Tail(uint? lines)
{
return _memoryLogger.Tail(lines);
}
public string[] GetNewLines()
{
return _memoryLogger.GetNewLines();
}
public string[] GetLog()
{
return _memoryLogger.GetLogMessages();
}
2023-05-20 21:47:54 +02:00
}