ISendLogService.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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.Subscribe(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. CoroutineExtensionUtility.StartCoroutine(PostRequestTest(methodName, jsonString));
  44. }
  45. private IEnumerator PostRequestTest(string methodName, string jsonString)
  46. {
  47. string url = "https://fat2.qulivr.com/mr-navigator/v1/unity/log";
  48. Debug.Log(url + jsonString);
  49. using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  50. {
  51. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  52. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  53. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  54. foreach (var v in requestHeader)
  55. {
  56. webRequest.SetRequestHeader(v.Key, v.Value);
  57. }
  58. yield return webRequest.SendWebRequest();
  59. if (webRequest.error != null)
  60. {
  61. Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text + "\n" + methodName);
  62. //GameManager.Instance.text2.text = webRequest.error;
  63. }
  64. else
  65. {
  66. Debug.Log(webRequest.downloadHandler.text);
  67. }
  68. }
  69. }
  70. }
  71. public class SendLogInfo
  72. {
  73. public string level { get; set; }
  74. public string tag { get; set; }
  75. public string message { get; set; }
  76. }