using System.Collections; using System.Collections.Generic; using System.Text; using Blue; using LitJson; using UnityEngine; using UnityEngine.Networking; public interface ISendLogService : IService { /// /// 发送日志 /// /// 自定义参数 /// 要发送的日志信息 void SendLog(string level, string message); } public class SendLogService : ISendLogService { private Queue sendLogMessage; private Dictionary requestHeader = new Dictionary(); // header private BindableProperty MessageCount { get; set; } = new BindableProperty { Value = 0 }; public void OnInit() { requestHeader.Add("Content-Type", "application/json"); sendLogMessage = new Queue(); MessageCount.Register(newInt=> { PostMessage("", sendLogMessage.Dequeue()); }); } public void SendLog(string level, string message) { SendLogInfo sendHLog = new SendLogInfo(); sendHLog.level = level; sendHLog.tag = Application.productName; sendHLog.message = message; string json = JsonMapper.ToJson(sendHLog); sendLogMessage.Enqueue(json); MessageCount.Value += 1; } private void PostMessage(string methodName, string jsonString) { CoroutineSystem.Instance.StartCoroutine(PostRequestTest(methodName, jsonString)); } private IEnumerator PostRequestTest(string methodName, string jsonString) { string url = "https://api-fat1.ghz-tech.com/mr-navigator/v1/unity/log"; using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST")) { byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString); webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); foreach (var v in requestHeader) { webRequest.SetRequestHeader(v.Key, v.Value); } yield return webRequest.SendWebRequest(); if (webRequest.error != null) Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text + "\n" + methodName); } } } public class SendLogInfo { public string level; public string tag; public string message; }