44 lines
1.2 KiB
C#
44 lines
1.2 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using UnityEngine;
|
|
|
|
public class FileLogger : MonoBehaviour
|
|
{
|
|
private string logFilePath;
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
// 定义日志文件路径
|
|
logFilePath = Application.persistentDataPath + "/game_log.txt";
|
|
|
|
// 删除旧日志文件(如果存在)
|
|
if (File.Exists(logFilePath))
|
|
{
|
|
File.Delete(logFilePath);
|
|
}
|
|
|
|
// 注册自定义日志处理器
|
|
Application.logMessageReceived += HandleLog;
|
|
}
|
|
|
|
void OnDestroy()
|
|
{
|
|
// 注销自定义日志处理器
|
|
Application.logMessageReceived -= HandleLog;
|
|
}
|
|
|
|
void HandleLog(string logString, string stackTrace, LogType type)
|
|
{
|
|
// 将日志信息写入文件
|
|
using (StreamWriter writer = new StreamWriter(logFilePath, true))
|
|
{
|
|
writer.WriteLine($"[{type}] {logString}");
|
|
if (type == LogType.Error || type == LogType.Exception)
|
|
{
|
|
writer.WriteLine(stackTrace); // 如果是错误或异常,写入堆栈跟踪
|
|
}
|
|
}
|
|
}
|
|
}
|