LogSystem.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. logFilePath = Application.persistentDataPath + "/logs/" + UserProperty.userId + ".log";
  25. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  26. }
  27. public void Log(string message)
  28. {
  29. string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message;
  30. Debug.Log(logMessage);
  31. File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
  32. }
  33. public void LogError(string message)
  34. {
  35. string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - ERROR: " + message;
  36. Debug.LogError(logMessage);
  37. File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
  38. }
  39. public void LogWarning(string message)
  40. {
  41. string logMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - WARNING: " + message;
  42. Debug.LogWarning(logMessage);
  43. File.AppendAllText(logFilePath, logMessage + Environment.NewLine);
  44. }
  45. }