using System;
using System.IO;
using System.Text;
namespace StandardScene.MagCarSimulator
{
///
/// 模拟器日志:UI 回调 + 写入 exe 旁 log/ 目录。
///
public static class MagCarSimLog
{
private static readonly object SyncRoot = new object();
private static StreamWriter _writer;
private static bool _enabled = true;
private static string _logDirectory;
public static event Action MessageWritten;
public static string CurrentFilePath { get; private set; }
public static void Configure(MagCarSimConfig config)
{
lock (SyncRoot)
{
_enabled = config == null || config.EnableFileLog;
_logDirectory = ResolveLogDirectory(config?.LogDirectory);
if (_enabled)
{
EnsureWriterUnlocked();
}
else
{
CloseWriterUnlocked();
}
}
}
public static string GetLogDirectory()
{
return _logDirectory ?? ResolveLogDirectory("log");
}
public static void WriteLine(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}
MessageWritten?.Invoke(message);
if (!_enabled)
{
return;
}
lock (SyncRoot)
{
EnsureWriterUnlocked();
_writer?.WriteLine(message);
}
}
public static void Shutdown()
{
lock (SyncRoot)
{
if (_writer != null)
{
try
{
_writer.WriteLine($"===== 会话结束 {DateTime.Now:yyyy-MM-dd HH:mm:ss} =====");
}
catch
{
}
}
CloseWriterUnlocked();
}
}
private static void EnsureWriterUnlocked()
{
if (!_enabled)
{
return;
}
if (_writer != null)
{
return;
}
Directory.CreateDirectory(GetLogDirectory());
var fileName = $"magcar-sim_{DateTime.Now:yyyyMMdd}.log";
CurrentFilePath = Path.Combine(GetLogDirectory(), fileName);
_writer = new StreamWriter(CurrentFilePath, true, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))
{
AutoFlush = true
};
_writer.WriteLine($"[{DateTime.Now:HH:mm:ss}] 文件日志已启用: {CurrentFilePath}");
}
private static void CloseWriterUnlocked()
{
try
{
_writer?.Flush();
_writer?.Dispose();
}
catch
{
}
_writer = null;
}
private static string ResolveLogDirectory(string configuredPath)
{
if (string.IsNullOrWhiteSpace(configuredPath))
{
return Path.Combine(AppContext.BaseDirectory, "log");
}
return Path.IsPathRooted(configuredPath)
? configuredPath
: Path.Combine(AppContext.BaseDirectory, configuredPath);
}
}
}