ISendLogService.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Blue;
  5. using LitJson;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. public interface ISendLogService : IService
  9. {
  10. /// <summary>
  11. /// 发送日志
  12. /// </summary>
  13. /// <param name="level">自定义参数</param>
  14. /// <param name="message">要发送的日志信息</param>
  15. void SendLog(string level, string message);
  16. }
  17. public class SendLogService : ISendLogService
  18. {
  19. private Queue<string> sendLogMessage;
  20. private Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  21. private BindableProperty<int> MessageCount { get; set; } = new BindableProperty<int> { Value = 0 };
  22. public void OnInit()
  23. {
  24. requestHeader.Add("Content-Type", "application/json");
  25. sendLogMessage = new Queue<string>();
  26. MessageCount.Register(newInt=>
  27. {
  28. PostMessage("", sendLogMessage.Dequeue());
  29. });
  30. }
  31. public void SendLog(string level, string message)
  32. {
  33. SendLogInfo sendHLog = new SendLogInfo();
  34. sendHLog.level = level;
  35. sendHLog.tag = Application.productName;
  36. sendHLog.message = message;
  37. string json = JsonMapper.ToJson(sendHLog);
  38. sendLogMessage.Enqueue(json);
  39. MessageCount.Value += 1;
  40. }
  41. private void PostMessage(string methodName, string jsonString)
  42. {
  43. CoroutineSystem.Instance.StartCoroutine(PostRequestTest(methodName, jsonString));
  44. }
  45. private IEnumerator PostRequestTest(string methodName, string jsonString)
  46. {
  47. string url = "https://api-fat1.ghz-tech.com/mr-navigator/v1/unity/log";
  48. using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  49. {
  50. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  51. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  52. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  53. foreach (var v in requestHeader)
  54. {
  55. webRequest.SetRequestHeader(v.Key, v.Value);
  56. }
  57. yield return webRequest.SendWebRequest();
  58. if (webRequest.error != null)
  59. Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text + "\n" + methodName);
  60. }
  61. }
  62. }
  63. public class SendLogInfo
  64. {
  65. public string level;
  66. public string tag;
  67. public string message;
  68. }