我想将简单的记录器添加到我的应用程序中。为此,我要使用StreamWriter
。
代码:
private StreamWriter OutputStream;
OutputStream = new StreamWriter(this.LogFilePath, true);
// .... message - log from app
DateTime now = DateTime.Now;
message = string.Format("[{0:yyyy-MM-dd H:mm:ss}] {1}", now, message
if (OutputStream != null)
{
OutputStream.WriteLine(message);
OutputStream.Flush();
}
因此所有字符串都被正确捕获并且输出正确,但是有时它可以写空字符串并在结尾加上不可见的字符:
样本:
[1970-08-31 14:56:26] Command response -> !c:65:f9:1b:82:97
并且如果我选中此with some tool that can show invisible characters,则可以看到下一个:
结果是约600行日志-125 mb。
我有found的原因可能是下一个:
发生了。当您首先添加文件时,其大小会在目录(在NTFS中是事务性目录),然后是实际目录写入新数据。如果您关闭系统最终会在文件后附加大量空字节,因为与元数据(文件大小)写入不同,数据写入不是事务性的。
没有绝对解决方案。
也尝试过
与isControl
个其他类似的检查字符一起检查;
尝试输入Trim
个最后一个字符;
选中docs-看起来都正确
有什么建议吗?
如果有人遇到相同的问题-我的原因不明,我只能猜测...。但是我用日志系统重写了逻辑,并且错误消失了:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
public class EventLogger : MonoBehaviour
{
private string logFileName = "btlog.txt";
public bool EchoToConsole = true;
public bool AddTimeStamp = true;
public bool EnableFileStorage = true;
private string LogFilePath
{
get
{
return Path.Combine(Application.persistentDataPath, logFileName);
}
}
private static EventLogger Singleton = null;
const string format = "yyyy-MM-dd HH:mm:ss.fffffff";
public static EventLogger Instance
{
get { return Singleton; }
}
void Awake()
{
if (Singleton != null)
{
UnityEngine.Debug.LogError("Multiple EventLogger Singletons exist!");
return;
}
Singleton = this;
if (this.EnableFileStorage)
{
if (File.Exists(LogFilePath))
{
long length = new FileInfo(LogFilePath).Length;
int limit = 1024 * 1024 * 5; // 5mb
if (length > limit)
{
File.Delete(LogFilePath);
Log("log file removed");
}
}
Log("-------------------");
Log("NEW SESSION STARTED");
}
}
private async Task Write(string message)
{
if (this.EnableFileStorage)
{
if (AddTimeStamp)
{
DateTime now = DateTime.Now;
string strDate = now.ToString(format);
string trimmed = new string(message.Where(c => !char.IsControl(c)).ToArray());
message = string.Format("[{0}] {1}", strDate, trimmed);
}
using (StreamWriter outputStream = new StreamWriter(this.LogFilePath, true))
{
await outputStream.WriteLineAsync(message);
}
if (EchoToConsole)
{
UnityEngine.Debug.Log(message);
}
}
}
[Conditional("DEBUG"), Conditional("PROFILE")]
public static void Log(string Message)
{
if (EventLogger.Instance != null)
{
_ = EventLogger.Instance.Write(Message);
}
else
{
UnityEngine.Debug.Log(Message);
}
}
}