HttpsSendLog.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using LitJson;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. public class HttpsSendLog : MonoSingleton<HttpsSendLog>
  8. {
  9. private Queue<string> qSendLog;
  10. private float times;
  11. Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
  12. void Awake()
  13. {
  14. //http header 的内容
  15. requestHeader.Add("Content-Type", "application/json");
  16. }
  17. private void Start()
  18. {
  19. qSendLog = new Queue<string>();
  20. times = 0;
  21. // SendLog("Error", "ceshi 11111111111");
  22. }
  23. public void SendLog(string tag,string message)
  24. {
  25. SendHttpsWriteLog sendHLog = new SendHttpsWriteLog();
  26. sendHLog.level = tag;
  27. sendHLog.tag = Application.productName;
  28. sendHLog.message = message;
  29. string json = JsonMapper.ToJson(sendHLog);
  30. qSendLog.Enqueue(json);
  31. }
  32. private void Update()
  33. {
  34. times += Time.deltaTime;
  35. if(times>1&&qSendLog.Count>0)
  36. {
  37. PostTest("", qSendLog.Dequeue());
  38. }
  39. }
  40. public void PostTest(string methodName, string jsonString)
  41. {
  42. StartCoroutine(PostRequestTest(methodName, jsonString));
  43. }
  44. private IEnumerator PostRequestTest(string methodName, string jsonString)
  45. {
  46. string url = "https://fat2.qulivr.com/mr-navigator/v1/unity/log";
  47. Debug.Log(url + jsonString);
  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. {
  60. Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text + "\n" + methodName);
  61. //GameManager.Instance.text2.text = webRequest.error;
  62. }
  63. else
  64. {
  65. Debug.Log(webRequest.downloadHandler.text);
  66. }
  67. }
  68. }
  69. }
  70. public class SendHttpsWriteLog
  71. {
  72. public string level { get; set; }
  73. public string tag { get; set; }
  74. public string message { get; set; }
  75. }