using System.Text;
namespace CanCommon;
///
/// Tees output to the console and a log file. The log ends with a machine-readable
/// SUMMARY key=value block so a report script can build the comparison table.
///
public sealed class RunLogger : IDisposable
{
private readonly StreamWriter _file;
public string Path { get; }
public RunLogger(string path)
{
Path = path;
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))!);
_file = new StreamWriter(path, append: false) { AutoFlush = true };
}
/// Console + file.
public void Line(string text = "")
{
Console.WriteLine(text);
_file.WriteLine(text);
}
/// File only (e.g. per-second samples we don't want to spam the log with twice).
public void FileOnly(string text)
{
_file.WriteLine(text);
}
/// Emit a machine-readable summary line: SUMMARY key1=v1 key2=v2 ....
public void Summary(IReadOnlyDictionary kv)
{
var sb = new StringBuilder("SUMMARY");
foreach (var (k, v) in kv) sb.Append(' ').Append(k).Append('=').Append(v);
Line(sb.ToString());
}
public void Dispose() => _file.Dispose();
/// Build a timestamped log path, e.g. results/can_master_can_com3_500k_20260815-093012.log
public static string BuildPath(string dir, string role, string iface, int bitrate)
{
string rate = bitrate switch
{
1_000_000 => "1m",
500_000 => "500k",
_ => $"{bitrate / 1000}k",
};
string ts = DateTime.Now.ToString("yyyyMMdd-HHmmss");
return System.IO.Path.Combine(dir, $"can_{role}_{iface}_{rate}_{ts}.log");
}
}