当前位置: 首页 > backend >正文

Unity 日志存档功能

一、问题:Windows系统路径中生成的日志文件没有历史记录,
二、方案:程序每次运行时都生成一份日志文件,这样就可以有历史记录了
三、拓展:有历史记录了,但如何保证程序异常退出时日志依然不会丢失呢
使用固定时间自动保存一次

using UnityEngine;
using System.Collections.Concurrent;
using System.IO;
using System.Collections;
using System;public class LogBackup : MonoBehaviour
{private ConcurrentQueue<string> logBuffer = new ConcurrentQueue<string>();private string logDirectory;private string currentLogFile;private bool isSaving = false;[Tooltip("是否记录代码堆栈信息")]public bool CodeInfo = false;[Tooltip("自动保存间隔(秒)")]public float AutoSaveInterval = 5f;public bool UseDebugModel = true;void Awake(){}private void Start(){UseDebugModel = XMLConfig.Instance.GetBool("UseDebugModel");if (!UseDebugModel){gameObject.SetActive(false);}else{InitializeLogSystem();Application.logMessageReceived += HandleLog;Application.quitting += SaveAndClose;// 启动自动保存协程StartCoroutine(AutoSaveRoutine());}}void OnDestroy(){Application.logMessageReceived -= HandleLog;Application.quitting -= SaveAndClose;StopAllCoroutines();}void InitializeLogSystem(){logDirectory = Path.Combine(Application.persistentDataPath, "GameLogs");Directory.CreateDirectory(logDirectory);CreateNewLogFile();}void CreateNewLogFile(){string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");currentLogFile = Path.Combine(logDirectory, $"RunLog_{timestamp}.txt");File.WriteAllText(currentLogFile, string.Empty); // 清空旧文件}void HandleLog(string logString, string stackTrace, LogType type){string formattedLog = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{type}] {logString}";if (CodeInfo && !string.IsNullOrEmpty(stackTrace)){formattedLog += $"\nStack Trace:\n{stackTrace}";}logBuffer.Enqueue(formattedLog + "\n");}IEnumerator AutoSaveRoutine(){while (true){yield return new WaitForSeconds(AutoSaveInterval);if (!isSaving) SaveLogs();}}void SaveAndClose(){Debug.Log("程序结束,存档");SaveLogs();// 强制立即保存(针对强制关机场景)ForceSave();}void SaveLogs(){if (logBuffer.IsEmpty || isSaving) return;isSaving = true;try{using (StreamWriter writer = new StreamWriter(currentLogFile, true)){writer.AutoFlush = true; // 关键:自动刷盘while (logBuffer.TryDequeue(out string log)){writer.Write(log);}}//Debug.Log($"Logs saved to: {currentLogFile}");}catch (Exception e){Debug.LogError($"Log save failed: {e.Message}");}finally{isSaving = false;}}void ForceSave(){// 最后一次紧急保存(尝试立即写入)if (logBuffer.TryDequeue(out string log)){try{File.AppendAllText(currentLogFile, log);}catch (Exception ex) { Debug.Log(ex);/* 无法恢复的错误 */ }}}#if UNITY_EDITORvoid Update(){if (Input.GetKeyDown(KeyCode.S)){SaveLogs();}}
#endif
}
http://www.xdnf.cn/news/5032.html

相关文章:

  • 数字化转型:概念性名词浅谈(第二十六讲)
  • c++ 命名空间
  • java的输入输出模板(ACM模式)
  • 软件测试——用例篇(2)
  • JavaScript与TypeScript深度对比分析
  • C++中volatile关键字详解
  • 赤色世界 陈默传 第一章 另一个陈默
  • 课程设计。。。。
  • 【C++设计模式之Strategy策略模式】
  • ISP流程介绍(Rgb格式阶段)
  • Java 原生实现代码沙箱(OJ判题系统第1期)——设计思路、实现步骤、代码实现
  • MySQL——七、索引
  • ArrayList和LinkedList区别
  • nginx的学习笔记
  • Android屏蔽通话功能和短信功能
  • AD 电阻容模型的创建
  • 68、微服务保姆教程(十一)微服务的监控与可观测性
  • 乌班图安装docker
  • 1.3.2 linux音频PulseAudio详细介绍
  • 关系模式-无损连接和保持函数依赖的判断
  • 用Python解密霍格沃茨的情感密码:哈利波特系列文本挖掘之旅
  • 用 Java 实现一个简单的阻塞队列
  • HTML字符串转换为React元素实现
  • 云轴科技ZStack入选赛迪顾问2025AI Infra平台市场发展报告代表厂商
  • LeetCode 1722. 执行交换操作后的最小汉明距离 题解
  • Filecoin存储管理:如何停止Lotus向特定存储路径写入新扇区数据
  • 【杂谈】-认知的范式革命:从逻辑理性到类比思维
  • 什么是AI写作
  • Rust 中的 Pin 和 Unpin:内存安全与异步编程的守护者
  • Typora+PicGo+Gitee图床配置教程 自动图片上传