服务器"/>
Unity使用UnityWebRequest实现本地日志上传到web服务器
一、前言
Unity项目开发中,遇到bug的时候,我们一般是通过日志来定位问题,所以写日志到本地文件,或者把日志文件上传到web服务器这样的功能就很必要了。下面就介绍下如何实现日志写入本地文件和上传本地日志文件到web服务器。
二、运行效果
三、Unity场景
创建场景,创建UI界面
创建Main.cs
脚本(代码见文章最下面),挂到Main Camera
上,绑定UI对象
四、Main.cs代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.IO;
using System.Text;public class Main : MonoBehaviour {public Button writeLogBtn;public Text logText;public Text progressLbl;public Slider progressSlider;public Button uploadBtn;const string UPLOAD_URL = "你上传日志的Http接口URL";string m_logFileSavePath;StringBuilder m_logStr = new StringBuilder();void Awake () {m_logFileSavePath = string.Format("{0}/output.log", Application.persistentDataPath);Application.logMessageReceived += LogCallBack;writeLogBtn.onClick.AddListener (() => {Debug.Log("write log test");});uploadBtn.onClick.AddListener (() => {byte[] data = ReadLogFile();Debug.Log(data.Length);StartCoroutine(HttpPost(UPLOAD_URL, data));});}// 输出日志回调void LogCallBack(string condition, string stackTrace, LogType type){m_logStr.Append (condition);m_logStr.Append ("\n");m_logStr.Append (stackTrace);m_logStr.Append ("\n");logText.text += m_logStr.ToString ();WriteLogToFile ();}// 将日志写入本地文件中void WriteLogToFile(){if (m_logStr.Length <= 0) return;if (!File.Exists (m_logFileSavePath)) {var fs = File.Create (m_logFileSavePath);fs.Close ();}using (var sw = File.AppendText (m_logFileSavePath)) {sw.WriteLine (m_logStr.ToString ());m_logStr.Remove (0, m_logStr.Length);}}// 读取日志文件的字节流byte[] ReadLogFile(){byte[] data = null;using (FileStream fs = File.OpenRead (m_logFileSavePath)) {int index = 0;long len = fs.Length;data = new byte[len];int offset = data.Length > 1024 ? 1024 : data.Length;while (index < len) {int readByteCnt = fs.Read (data, index, offset);index += readByteCnt;long leftByteCnt = len - index;offset = leftByteCnt > offset ? offset : (int)leftByteCnt;}Debug.Log ("Read Done");}return data;}// 将日志字节流上传到web服务器IEnumerator HttpPost(string url, byte[] data){WWWForm form = new WWWForm ();form.AddField ("desc", "test upload log file");form.AddBinaryData ("errlog", data, "test_log.txt", "application/x-gzip");// 使用UnityWebRequestUnityWebRequest request = UnityWebRequest.Post (url, form);var result = request.Send ();if (request.isError) {Debug.LogError (request.error);}while (!result.isDone) {yield return null;// 更新上传日志进度条progressSlider.value = request.uploadProgress;progressLbl.text = request.uploadProgress * 100 + "%";Debug.Log ("result.progress: " + request.uploadProgress);}Debug.Log ("finish upload, http return msg: \n" + request.downloadHandler.text);}
}
更多推荐
Unity使用UnityWebRequest实现本地日志上传到web服务器
发布评论