2024-12-09 10:17:47 +01:00
|
|
|
|
using Utils;
|
|
|
|
|
|
|
|
|
|
|
|
namespace Logging
|
2023-04-12 13:53:55 +02:00
|
|
|
|
{
|
|
|
|
|
|
public class LogFile
|
|
|
|
|
|
{
|
2023-04-25 13:43:51 +02:00
|
|
|
|
private readonly object fileLock = new object();
|
2023-04-12 13:53:55 +02:00
|
|
|
|
|
2025-01-16 10:15:02 +01:00
|
|
|
|
public LogFile(string filename)
|
2023-04-12 13:53:55 +02:00
|
|
|
|
{
|
2025-01-16 10:15:02 +01:00
|
|
|
|
Filename = filename;
|
2023-04-12 13:53:55 +02:00
|
|
|
|
|
2023-04-14 14:53:39 +02:00
|
|
|
|
EnsurePathExists(filename);
|
2023-04-12 13:53:55 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-01-16 10:15:02 +01:00
|
|
|
|
public string Filename { get; private set; }
|
2023-04-12 13:53:55 +02:00
|
|
|
|
|
|
|
|
|
|
public void Write(string message)
|
|
|
|
|
|
{
|
|
|
|
|
|
WriteRaw($"{GetTimestamp()} {message}");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public void WriteRaw(string message)
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
2023-04-25 13:43:51 +02:00
|
|
|
|
lock (fileLock)
|
|
|
|
|
|
{
|
2025-01-16 10:15:02 +01:00
|
|
|
|
File.AppendAllLines(Filename, new[] { message });
|
2023-04-25 13:43:51 +02:00
|
|
|
|
}
|
2023-04-12 13:53:55 +02:00
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
Console.WriteLine("Writing to log has failed: " + ex);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-02-03 10:47:37 +01:00
|
|
|
|
public void WriteRawMany(IEnumerable<string> lines)
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
lock (fileLock)
|
|
|
|
|
|
{
|
|
|
|
|
|
File.AppendAllLines(Filename, lines);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
Console.WriteLine("Writing to log has failed: " + ex);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-04-12 13:53:55 +02:00
|
|
|
|
private static string GetTimestamp()
|
|
|
|
|
|
{
|
2024-12-09 10:17:47 +01:00
|
|
|
|
return $"[{Time.FormatTimestamp(DateTime.UtcNow)}]";
|
2023-04-12 13:53:55 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2023-04-14 14:53:39 +02:00
|
|
|
|
private void EnsurePathExists(string filename)
|
2023-04-12 13:53:55 +02:00
|
|
|
|
{
|
2023-04-14 14:53:39 +02:00
|
|
|
|
var path = new FileInfo(filename).Directory!.FullName;
|
|
|
|
|
|
Directory.CreateDirectory(path);
|
2023-04-12 13:53:55 +02:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|