捕获程序异常并输出Log到屏幕上

来源:互联网 发布:linux时间不准确 编辑:程序博客网 时间:2024/06/04 20:11
将该脚本挂到场景中任意的GameObjec上,这样在移动端上就可以显示Log信息,并捕获程序异常
using UnityEngine;using System.Collections;using System.Collections.Generic;using System.IO;using System.Text;using System;using System.Net.Sockets;public class ULog : MonoBehaviour{    static List mLines = new List();    static List mWriteTxt = new List();    private string outpath;    ///     /// 是否输出日志到界面上    ///     public bool isOutputScreen = true;    ///     /// 是否记录日志    ///     static public bool IsDebug = true;    //------------------scroll view--------------    public Vector2 scrollPosition = Vector2.zero;    public float scrollVelocity = 0f;    public float timeTouchPhaseEnded = 0f;    public float inertiaDuration = 0.5f;    public Vector2 lastDeltaPos;    //-------------------------------------------    void Start()    {        //Application.persistentDataPath Unity中只有这个路径是既可以读也可以写的。        if (Application.platform == RuntimePlatform.WindowsEditor)        {            outpath = Application.dataPath + "/UnityLog.txt";        }        else//android        {            outpath = Application.persistentDataPath + "/UnityLog.txt";        }        //每次启动客户端删除之前保存的Log        if (System.IO.File.Exists(outpath))        {            File.Delete(outpath);        }        //在这里做一个Log的监听        Application.logMessageReceived += HandleLog;    }    ///     /// 记录日志    ///     /// #if UNITY_EDITOR    public static Action Log = Debug.Log;#else static public void Log(string log)    {        if (IsDebug)        {            Debug.Log(log);        }    }#endif    ///     /// 记录错误日志    ///     ///     static public void LogError(string error)    {        if (IsDebug)        {            Debug.LogError(error);        }    }    ///     /// 记录警告日志    ///     ///     static public void LogWarning(string warning)    {        if (IsDebug)        {            Debug.LogWarning(warning);        }    }    ///     /// 记录异常日志    ///     ///     static public void LogException(Exception e)    {        if (IsDebug)        {            Debug.LogException(e);            if (e is SocketException)            {                //输出Log到文件                if (!string.IsNullOrEmpty(e.Message))                    mWriteTxt.Add(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + " : " + e.Message);                if (!string.IsNullOrEmpty(e.StackTrace))                    mWriteTxt.Add(e.StackTrace);            }        }    }    ///     /// Log写入文件    ///     ///     ///     ///     void Update()    {        if (IsDebug)        {            //因为写入文件的操作必须在主线程中完成,所以在Update中哦给你写入文件。            if (mWriteTxt.Count > 0)            {                string[] temp = mWriteTxt.ToArray();                foreach (string t in temp)                {                    using (StreamWriter writer = new StreamWriter(outpath, true, Encoding.UTF8))                    {                        writer.WriteLine(t);                    }                    mWriteTxt.Remove(t);                }            }            if (Input.touchCount > 0)            {                if (Input.GetTouch(0).phase == TouchPhase.Moved)                {                    scrollPosition.y += Input.GetTouch(0).deltaPosition.y * 5;                    lastDeltaPos = Input.GetTouch(0).deltaPosition;                }                else if (Input.GetTouch(0).phase == TouchPhase.Ended)                {                    if (Mathf.Abs(lastDeltaPos.y) > 5.0f)                    {                        scrollVelocity = (int)(lastDeltaPos.y * 0.5 / Input.GetTouch(0).deltaTime);                        //print(scrollVelocity);                    }                    timeTouchPhaseEnded = Time.time;                }            }            else            {                if (scrollVelocity != 0.0f)                {                    // slow down                    float t = (Time.time - timeTouchPhaseEnded) / inertiaDuration;                    float frameVelocity = Mathf.Lerp(scrollVelocity, 0, t);                    scrollPosition.y += frameVelocity * Time.deltaTime;                    //if (t >= inertiaDuration)                    //    scrollVelocity = 0;                }            }        }    }    ///     /// Log侦听器    ///     ///     ///     ///     void HandleLog(string logString, string stackTrace, LogType type)    {        if (IsDebug)        {            //输出Log到文件            if (!string.IsNullOrEmpty(logString))                mWriteTxt.Add(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "   " + type.ToString() + " : " + logString);            if (!string.IsNullOrEmpty(stackTrace))                mWriteTxt.Add(stackTrace);            //输出Log到屏幕            if (type == LogType.Error || type == LogType.Exception || type == LogType.Log)            {                ShowLog(logString);                ShowLog(stackTrace);            }        }    }    ///     /// 这里我把错误的信息保存起来,用来输出在手机屏幕上    ///     ///     static public void ShowLog(params object[] objs)    {        string text = "";        for (int i = 0; i < objs.Length; ++i)        {            if (i == 0)            {                text += objs[i].ToString();            }            else            {                text += ", " + objs[i].ToString();            }        }        if (Application.isPlaying)        {            if (mLines.Count > 25)            {                mLines.RemoveAt(0);            }            mLines.Add(text);        }    }    void OnGUI()    {        if (IsDebug)        {            if (isOutputScreen)            {                scrollPosition = GUI.BeginScrollView(new Rect(0, 0, 800, Screen.height), scrollPosition, new Rect(0, 0, 790, 2000), false, true);                GUIStyle style = new GUIStyle();                style.fontSize = 25;                GUI.color = Color.white;                style.wordWrap = true;                style.fixedWidth = 800;                for (int i = 0, imax = mLines.Count; i < imax; ++i)                {                    GUILayout.Label(mLines[i], style);                }                GUI.EndScrollView();            }            if (GUI.Button(new Rect(0, 0, 100, 100), "Show"))            {                if (isOutputScreen)                {                    isOutputScreen = false;                }                else                {                    isOutputScreen = true;                }            }        }    }}                                             
0 0
原创粉丝点击