ISendLogService.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. void SendLog(string tag, string message);
  11. }
  12. public class SendLogService : ISendLogService
  13. {
  14. private Queue<string> sendLogMessage;
  15. private Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  16. private BindableProperty<int> MessageCount { get; set; } = new BindableProperty<int> { Value = 0 };
  17. public void OnInit()
  18. {
  19. requestHeader.Add("Content-Type", "application/json");
  20. sendLogMessage = new Queue<string>();
  21. MessageCount.Subscribe(newInt=>
  22. {
  23. PostMessage("", sendLogMessage.Dequeue());
  24. });
  25. }
  26. public void SendLog(string level, string message)
  27. {
  28. SendLogInfo sendHLog = new SendLogInfo();
  29. sendHLog.level = level;
  30. sendHLog.tag = Application.productName;
  31. sendHLog.message = message;
  32. string json = JsonMapper.ToJson(sendHLog);
  33. sendLogMessage.Enqueue(json);
  34. MessageCount.Value += 1;
  35. }
  36. private void PostMessage(string methodName, string jsonString)
  37. {
  38. CoroutineExtensionUtility.StartCoroutine(PostRequestTest(methodName, jsonString));
  39. }
  40. private IEnumerator PostRequestTest(string methodName, string jsonString)
  41. {
  42. string url = "https://fat2.qulivr.com/mr-navigator/v1/unity/log";
  43. Debug.Log(url + jsonString);
  44. using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  45. {
  46. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  47. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  48. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  49. foreach (var v in requestHeader)
  50. {
  51. webRequest.SetRequestHeader(v.Key, v.Value);
  52. }
  53. yield return webRequest.SendWebRequest();
  54. if (webRequest.error != null)
  55. {
  56. Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text + "\n" + methodName);
  57. //GameManager.Instance.text2.text = webRequest.error;
  58. }
  59. else
  60. {
  61. Debug.Log(webRequest.downloadHandler.text);
  62. }
  63. }
  64. }
  65. }
  66. public class SendLogInfo
  67. {
  68. public string level { get; set; }
  69. public string tag { get; set; }
  70. public string message { get; set; }
  71. }