58 lines
1.5 KiB
C#
58 lines
1.5 KiB
C#
namespace ConsoleApp.Logging;
|
|
|
|
public sealed class ConsoleLog : IDisposable
|
|
{
|
|
private readonly StreamWriter _file;
|
|
|
|
private ConsoleLog(string filePath, DateTime startedAt)
|
|
{
|
|
FilePath = filePath;
|
|
StartedAt = startedAt;
|
|
_file = new StreamWriter(filePath, append: true) { AutoFlush = true };
|
|
_file.WriteLine($"Запуск: {startedAt:yyyy-MM-dd HH:mm:ss}");
|
|
}
|
|
|
|
public string FilePath { get; }
|
|
|
|
public DateTime StartedAt { get; }
|
|
|
|
public static ConsoleLog Open(string? fileName = null)
|
|
{
|
|
var startedAt = TruncateToSeconds(DateTime.Now);
|
|
fileName ??= $"test-sms-console-app-{startedAt:yyyyMMdd_HHmmss}.log";
|
|
return new ConsoleLog(Path.GetFullPath(fileName), startedAt);
|
|
}
|
|
|
|
private static DateTime TruncateToSeconds(DateTime value) =>
|
|
new(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, value.Kind);
|
|
|
|
public void Write(string? text)
|
|
{
|
|
Console.Write(text);
|
|
_file.Write(text);
|
|
}
|
|
|
|
public void WriteLine(string? text = null)
|
|
{
|
|
if (text is null)
|
|
{
|
|
Console.WriteLine();
|
|
_file.WriteLine();
|
|
return;
|
|
}
|
|
|
|
Console.WriteLine(text);
|
|
_file.WriteLine(text);
|
|
}
|
|
|
|
public string? ReadLine(string prompt)
|
|
{
|
|
Write(prompt);
|
|
var line = Console.ReadLine();
|
|
_file.WriteLine(line ?? "");
|
|
return line;
|
|
}
|
|
|
|
public void Dispose() => _file.Dispose();
|
|
}
|