操作控制台输出流(添加时间戳)



在我的项目中,我需要调整unity日志文件,为了可读性,我需要在输出中添加时间戳。对于Debug.Log输出,我可以为具有Application.logMessageReceivedThreaded的消息添加回调,并重定向和修改输出。

但是我使用的是一个dll,我为它编写了一个包装。这个dll有一些消息也需要进入我的日志据我所知,输出将流式传输到控制台流中,我知道我可以使用Console.SetOut重定向消息。但是消息也需要一个时间戳,据我所知,没有办法修改控制台流的内容

我知道Unity最近添加了一个参数,在日志中包含时间戳前缀,但没有关于实际命令的文档,至少在编辑器中他们也添加了线程ID(我不需要(。

我不确定反射发射是否可能,即使可能,我也不知道这是否是最好的方法。

目前我的脚本是这样的:

public class ApplicationLogger : Singleton<ApplicationLogger>
{
string path;
string file;
private StreamWriter writer;
private StreamWriter standardOutput;
void OnEnable()
{
#if !UNITY_EDITOR
if (System.Environment.GetCommandLineArgs().Length > 2)
{
path = System.Environment.GetCommandLineArgs()[2] + @"/log";
file = System.Environment.GetCommandLineArgs()[2] + @"/log/Unity.log";
}
Application.logMessageReceivedThreaded += HandleLog;
#endif

standardOutput = new StreamWriter(Console.OpenStandardOutput());
writer = new StreamWriter(file);
Console.SetOut(writer);
}
void OnDisable()
{
writer.Flush();
writer.Close();
Console.SetOut(standardOutput);
#if !UNITY_EDITOR
Application.logMessageReceivedThreaded -= HandleLog;
#endif
}
void HandleLog(string logString, string stackTrace, LogType type)
{
UnityMainThreadDispatcher.Instance().Enqueue(() => WriteFile(logString, stackTrace, type));
}
void WriteFile(string logString, string stackTrace, LogType type)
{
writer.WriteLine($"[{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")}] " + logString);
if (LogType.Error == type || LogType.Exception == type)
{
writer.WriteLine(stackTrace);
}
writer.WriteLine();
writer.Flush();
}
}

有了这个,我至少有了我需要的所有消息,但只有Unity输出有时间戳

为什么不实现自己的流编写器?

class MyTextWriter : System.IO.StreamWriter
{
public MyTextWriter(string path) : base(path) { }
public override void WriteLine(string value)
{
base.WriteLine($"[{System.DateTime.Now.ToShortTimeString()}] {value}");
}
}

最新更新