Unity写Log到文本

分享一篇输出Unity Log到文本的脚本。
在手机上调试看Log相当方便,不用写一堆OnGUI做显示,OnGUI还容易写错出问题。

/*
 * By: Fox.Huang 黄文叶, Date:2018.12.18
 */
using UnityEngine;
using System.IO;

public class DebugLogOutput
{
	static bool s_HasInit = false;
	static string s_LogPath = null;

	static int s_LastCount = 0;		// 这个变量相关的逻辑,是用来做重新信息处理的.因为有时候错误会噼里啪啦的跳,减缓一点IO压力.
	static string s_LastLog = "";

	public static void InitLogFile(string logPath)
	{
		if (!string.IsNullOrEmpty(logPath))
		{
			s_HasInit = true;
			s_LogPath = logPath;
		}
	}

	public static void HandleLog(string logString, string stackTrace, LogType type)
	{
		if (s_HasInit)
		{
			string logContent = "[" + type.ToString() + "]" + logString;

			if (s_LastCount < 10 || s_LastLog != logContent)
			{
				if (s_LastLog == logContent)
				{
					++s_LastCount;
				}
				else
				{
					s_LastCount = 1;
					s_LastLog = logContent;
				}
				using (StreamWriter sw = new StreamWriter(s_LogPath, true, System.Text.Encoding.GetEncoding("UTF-8")))
				{
					sw.WriteLine(logContent);
					sw.Close();
				}
			}
		}
	}
}

然后是使用的部分


		DebugLogOutput.InitLogFile(Application.persistentDataPath + "/Log.txt");// 初始化需要输出的路径
		
		Application.logMessageReceived += DebugLogOutput.HandleLog;//添加监听		
		Application.logMessageReceived -= DebugLogOutput.HandleLog;//移除监听

程序学无止尽。
欢迎大家沟通,有啥不明确的,或者不对的,也可以和我私聊
我的QQ 334524067 神一般的狄狄

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值