ISendLogService.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. CoroutineUtility.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. }
  63. else
  64. {
  65. Debug.Log(webRequest.downloadHandler.text);
  66. }
  67. }
  68. }
  69. }