HttpsSendLog.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using LitJson;
  2. using SC.XR.Unity;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. public class HttpsSendLog : MonoBehaviour
  9. {
  10. private static HttpsSendLog instance;
  11. public static HttpsSendLog Instance
  12. {
  13. get
  14. {
  15. return instance;
  16. }
  17. }
  18. private HttpsSendLog()
  19. {
  20. }
  21. private Queue<string> qSendLog;
  22. private float times;
  23. Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  24. void Awake()
  25. {
  26. instance = GetComponent<HttpsSendLog>();
  27. //http header 的内容
  28. requestHeader.Add("Content-Type", "application/json");
  29. }
  30. private void Start()
  31. {
  32. qSendLog = new Queue<string>();
  33. times = 0;
  34. // SendLog("Error", "ceshi 11111111111");
  35. }
  36. public void SendLog(string tag,string message)
  37. {
  38. SendHttpsWriteLog sendHLog = new SendHttpsWriteLog();
  39. sendHLog.level = tag;
  40. sendHLog.tag = Application.productName;
  41. sendHLog.message = message;
  42. string json = JsonMapper.ToJson(sendHLog);
  43. qSendLog.Enqueue(json);
  44. }
  45. private void Update()
  46. {
  47. times += Time.deltaTime;
  48. if(times>1&&qSendLog.Count>0)
  49. {
  50. PostTest("", qSendLog.Dequeue());
  51. }
  52. }
  53. public void PostTest(string methodName, string jsonString)
  54. {
  55. StartCoroutine(PostRequestTest(methodName, jsonString));
  56. }
  57. private IEnumerator PostRequestTest(string methodName, string jsonString)
  58. {
  59. string url = "https://fat2.qulivr.com/mr-navigator/v1/unity/log";
  60. Debug.Log(url + jsonString);
  61. using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
  62. {
  63. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  64. webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  65. webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  66. foreach (var v in requestHeader)
  67. {
  68. webRequest.SetRequestHeader(v.Key, v.Value);
  69. }
  70. yield return webRequest.SendWebRequest();
  71. if (webRequest.error!=null)
  72. {
  73. Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text + "\n" + methodName);
  74. //GameManager.Instance.text2.text = webRequest.error;
  75. }
  76. else
  77. {
  78. Debug.Log(webRequest.downloadHandler.text);
  79. }
  80. }
  81. }
  82. }
  83. public class SendHttpsWriteLog
  84. {
  85. public string level { get; set; }
  86. public string tag { get; set; }
  87. public string message { get; set; }
  88. }