LogSystem.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IO;
  3. using UnityEngine;
  4. /* 本文件为日志系统的实现
  5. * 该系统用于记录游戏运行时的日志信息,包括普通日志、错误日志和警告日志
  6. * 日志信息将被保存到指定路径的文件中,便于后续查看和分析
  7. */
  8. public class LogSystem : MonoBehaviour
  9. {
  10. public static LogSystem Instance { get; private set; }
  11. private string logFilePath;
  12. private void Awake()
  13. {
  14. if (Instance == null)
  15. {
  16. Instance = this;
  17. DontDestroyOnLoad(gameObject);
  18. }
  19. else
  20. {
  21. Destroy(gameObject);
  22. }
  23. // 设置日志文件路径
  24. DateTime now = DateTime.Now;
  25. logFilePath = Application.persistentDataPath + "/logs/" + now.ToString("yyyy-MM-dd") + UserProperty.userId + ".log";
  26. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  27. }
  28. public void Log(string message)
  29. {
  30. string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message;
  31. Debug.Log(logMessage);
  32. File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
  33. }
  34. public void LogError(string message)
  35. {
  36. string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - ERROR: " + message;
  37. Debug.LogError(logMessage);
  38. File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
  39. }
  40. public void LogWarning(string message)
  41. {
  42. string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - WARNING: " + message;
  43. Debug.LogWarning(logMessage);
  44. File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
  45. }
  46. }