using UnityEngine; using UnityEngine.Networking; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; public class CloudLogger : MonoBehaviour { // ============================================================ // ★ 只需修改这两行,填入你注册时的用户名和密码 // ============================================================ public string USERNAME = "你的用户名"; public string PASSWORD = "你的密码"; // ============================================================ private const string SERVER = "https://aipeizhen.cn"; private const float FLUSH_INTERVAL = 0.5f; private const int MAX_BATCH = 50; private const string TAG = "[CloudLogger]"; public static CloudLogger Instance; private string _token = ""; private bool _ready = false; private struct LogEntry { public string msg; public string level; public string stack; public int seq; } private readonly Queue _queue = new Queue(); private readonly object _lock = new object(); private int _seq = 0; void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); } void Start() { StartCoroutine(LoginThenStart()); } IEnumerator LoginThenStart() { string body = "{\"username\":\"" + USERNAME + "\",\"password\":\"" + PASSWORD + "\"}"; using (UnityWebRequest req = new UnityWebRequest(SERVER + "/login", "POST")) { req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(body)); req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); yield return req.SendWebRequest(); if (req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.DataProcessingError) { // 断网,无法联通服务器,只能写死 Debug.LogError(TAG + " 登录失败(网络连接错误):" + req.error); } else { string respBody = req.downloadHandler.text; _token = ParseToken(respBody); if (!string.IsNullOrEmpty(_token)) { _ready = true; Application.logMessageReceivedThreaded += OnLog; InvokeRepeating("Flush", FLUSH_INTERVAL, FLUSH_INTERVAL); Debug.Log(TAG + " 登录成功,开始上传日志"); } else { string reason = ParseError(respBody, "登录失败,请检查用户名和密码"); Debug.LogError(TAG + " " + reason); } } } } void OnDestroy() { _ready = false; // ← 先标记不可用,防止 OnLog 继续入队 Application.logMessageReceivedThreaded -= OnLog; CancelInvoke("Flush"); } private void OnLog(string condition, string stackTrace, LogType type) { if (!_ready) return; if (condition.StartsWith(TAG)) return; if (type == LogType.Assert) return; string level; if (type == LogType.Log) level = "INFO"; else if (type == LogType.Warning) level = "WARN"; else if (type == LogType.Error) level = "ERROR"; else if (type == LogType.Exception) level = "EXCEPTION"; else level = "INFO"; string stack = (level == "ERROR" || level == "EXCEPTION") ? stackTrace : ""; int s = Interlocked.Increment(ref _seq); LogEntry entry = new LogEntry(); entry.msg = condition; entry.level = level; entry.stack = stack; entry.seq = s; lock (_lock) { _queue.Enqueue(entry); } } /// /// 静默上传一条日志(不显示在 Unity Console) /// level 可选:INFO / WARN / ERROR / DEBUG /// public void Log(string msg, string level) { if (!_ready) return; int s = Interlocked.Increment(ref _seq); LogEntry entry = new LogEntry(); entry.msg = msg; entry.level = level; entry.stack = ""; entry.seq = s; lock (_lock) { _queue.Enqueue(entry); } } // 重载:不传 level 时默认 INFO public void Log(string msg) { Log(msg, "INFO"); } private void Flush() { if (!_ready || _queue.Count == 0) return; List batch = new List(); lock (_lock) { while (_queue.Count > 0 && batch.Count < MAX_BATCH) batch.Add(_queue.Dequeue()); } StartCoroutine(Send(batch)); } IEnumerator Send(List batch) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < batch.Count; i++) { if (i > 0) sb.Append(","); sb.Append("{\"seq\":" + batch[i].seq + ",\"level\":\"" + batch[i].level + "\"" + ",\"msg\":\"" + Esc(batch[i].msg) + "\"" + ",\"stack\":\"" + Esc(batch[i].stack) + "\"" + "}"); } string json = "{\"logs\":[" + sb + "],\"extra\":{\"version\":\"" + Esc(Application.version) + "\",\"platform\":\"" + Application.platform.ToString() + "\",\"device\":\"" + Esc(SystemInfo.deviceModel) + "\"}}"; using (UnityWebRequest req = new UnityWebRequest(SERVER + "/upload", "POST")) { req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json)); req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); req.SetRequestHeader("X-Token", _token); yield return req.SendWebRequest(); if (req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.DataProcessingError) { // 真正断网,服务器没有响应,只能写死 Debug.LogError(TAG + " 上传失败(网络连接错误):" + req.error); } else { long code = req.responseCode; if (code != 200) { string body = req.downloadHandler.text; string reason = ParseError(body, "上传失败(HTTP " + code + ")"); Debug.LogError(TAG + " 上传失败:" + reason); if (code == 401 || code == 403) { _ready = false; Application.logMessageReceivedThreaded -= OnLog; CancelInvoke("Flush"); Debug.LogError(TAG + " 已停止上传,请检查账号状态。"); } } } } } private string ParseToken(string json) { const string key = "\"token\":\""; int i = json.IndexOf(key); if (i < 0) return ""; i += key.Length; int j = json.IndexOf('"', i); return j < 0 ? "" : json.Substring(i, j - i); } private string ParseError(string json, string fallback) { const string key = "\"error\":\""; int i = json.IndexOf(key); if (i < 0) return fallback; i += key.Length; int j = json.IndexOf('"', i); return j < 0 ? fallback : json.Substring(i, j - i); } private string ParseError(string json) { return ParseError(json, "未知错误"); } private string Esc(string s) { if (string.IsNullOrEmpty(s)) return ""; return s.Replace("\\", "\\\\").Replace("\"", "\\\"") .Replace("\n", "\\n").Replace("\r", "\\r") .Replace("\t", "\\t"); } }