cs-codex-dist-tests/Logging/LogFile.cs

62 lines
1.5 KiB
C#
Raw Normal View History

2023-04-12 11:53:55 +00:00
namespace Logging
{
public class LogFile
{
2023-04-14 12:53:39 +00:00
private readonly string extension;
2023-04-25 11:43:51 +00:00
private readonly object fileLock = new object();
2023-04-14 12:53:39 +00:00
private string filename;
2023-04-12 11:53:55 +00:00
2023-04-14 12:53:39 +00:00
public LogFile(string filename, string extension)
2023-04-12 11:53:55 +00:00
{
2023-04-14 12:53:39 +00:00
this.filename = filename;
this.extension = extension;
FullFilename = filename + "." + extension;
2023-04-12 11:53:55 +00:00
2023-04-14 12:53:39 +00:00
EnsurePathExists(filename);
2023-04-12 11:53:55 +00:00
}
2023-04-14 12:53:39 +00:00
public string FullFilename { get; private set; }
2023-04-12 11:53:55 +00:00
public void Write(string message)
{
WriteRaw($"{GetTimestamp()} {message}");
}
public void WriteRaw(string message)
{
try
{
2023-04-25 11:43:51 +00:00
lock (fileLock)
{
File.AppendAllLines(FullFilename, new[] { message });
}
2023-04-12 11:53:55 +00:00
}
catch (Exception ex)
{
Console.WriteLine("Writing to log has failed: " + ex);
}
}
public void ConcatToFilename(string toAdd)
{
var oldFullName = FullFilename;
2023-04-14 12:53:39 +00:00
filename += toAdd;
FullFilename = filename + "." + extension;
2023-04-12 11:53:55 +00:00
File.Move(oldFullName, FullFilename);
}
private static string GetTimestamp()
{
return $"[{DateTime.UtcNow.ToString("o")}]";
2023-04-12 11:53:55 +00:00
}
2023-04-14 12:53:39 +00:00
private void EnsurePathExists(string filename)
2023-04-12 11:53:55 +00:00
{
2023-04-14 12:53:39 +00:00
var path = new FileInfo(filename).Directory!.FullName;
Directory.CreateDirectory(path);
2023-04-12 11:53:55 +00:00
}
}
}