DCS/ruiyiweiUX/Assets/GeneralTools/Scripts/Always/FileDebug.cs

119 lines
3.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;
namespace GeneralTools
{
public class FileDebug : SingletonBaseAttribute<FileDebug>
{
FileStream fileStream_log;
StreamWriter streamWrite_log;
Queue<LogItem> logQue = new Queue<LogItem>();
string dirPath = "";
public override void IAwake()
{
if (ConfigHelper.saveLog)
{
CreateTxt();
Application.logMessageReceived += LogHandler;
}
}
private void CreateTxt()
{
dirPath = DevicePath.CurrentDirectory + "/Log";
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
string fileName_log = dirPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "----" + "log" + ".txt";
fileStream_log = new FileStream(fileName_log, FileMode.OpenOrCreate, FileAccess.ReadWrite);
streamWrite_log = new StreamWriter(fileStream_log);
CheckLogFileNum(dirPath, 20);
}
public override void IOnApplicationQuit()
{
if (ConfigHelper.saveLog)
{
streamWrite_log.Close();
fileStream_log.Close();
Application.logMessageReceived -= LogHandler;
}
}
private void LogHandler(string condition, string stackTrace, LogType type)
{
logQue.Enqueue(new LogItem()
{
messageString = condition,
stackTrace = stackTrace,
logType = type,
time = DateTime.Now
});
}
private void FixedUpdate()
{
if (logQue.Count > 0)
{
try
{
var item = logQue.Peek(); // 取队首元素但先不移除
var timeStr = item.time.ToString("HH:mm:ss.ff");
var logStr = string.Format("{0}-[{1}]{2}======>{3}", timeStr, item.logType, item.messageString, item.stackTrace);
streamWrite_log.WriteLine(logStr);
streamWrite_log.Flush();
logQue.Dequeue(); // 成功执行了再移除队首元素
}
catch (IOException ex)
{
Debug.Log(ex.Message);
}
}
}
/// <summary>
/// 删除多余的Log
/// </summary>
/// <param name="path"></param>
/// <param name="maxNum"></param>
protected void CheckLogFileNum(string path, int maxNum)
{
List<string> pathList = Directory.GetFiles(path).ToList();
int deleteNum = pathList.Count - maxNum;
if (deleteNum > 0)
{
for (int i = 0; i < deleteNum; i++)
{
File.Delete(pathList[i]);
}
}
}
}
}
public struct LogItem
{
/// <summary>
/// 日志内容
/// </summary>
public string messageString;
/// <summary>
/// 调用堆栈
/// </summary>
public string stackTrace;
/// <summary>
/// 日志类型
/// </summary>
public LogType logType;
/// <summary>
/// 记录时间
/// </summary>
public DateTime time;
}