Uinty logo 日志本地保存

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class Write : MonoBehaviour
{
    private static FileStream FileWriter;
    private static UTF8Encoding encoding;
    private static Write _consoleLog;
    private static bool _AllDisplay;
    private static bool _LogDisplay;
    private static bool _WarningDisplay;
    private static bool _LogData;
    private static bool IsIDE;
    private FileInfo fileInfo;
    private string NowTime;

    private static DateTime mstartTime;
    private static TimeSpan ts1;
    private static string txtpath;
   

    public static Write console //开启单例
    {
        get
        {
            if (_consoleLog == null)
                _consoleLog = new Write();
            return _consoleLog;
        }
    }

    /// <summary>
    ///     开始写入日志,参数一:是否写入Warning类型数据,默认不写入,参数二:是否写入Debug.Log类型数据,默认不写入,参数三:是否写入全部数据,默认不写入,参数四:是否将Log方法信息输出到控制台,默认输出
    /// </summary>
    /// <param name="WarningDisplay"></param>
    public void LogStart(bool WarningDisplay = false, bool LogDisplay = false, bool AllDisplay = false,
        bool LogData = true)
    {

        if ((FileWriter == null))
        {
            IsIDE = Application.isEditor; //获取当前场景运行环境
            _WarningDisplay = WarningDisplay;
            _LogDisplay = LogDisplay;
            _AllDisplay = AllDisplay;
            _LogData = LogData;
            if (IsIDE == false) //判断当前场景运行环境,如果是Editor中则不执行
            {
                string logpath = Application.dataPath + "/StreamingAssets/" + "Log";

              //每次启动的时候  都要删除之前保存的日志,重新新建文件夹保存日志

if (Directory.Exists(logpath))
                {
                    DirectoryInfo file1 = new DirectoryInfo(logpath);
                    deleteDirs(file1);
                    file1 = null;
                }
                

                Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
                Directory.CreateDirectory(Application.dataPath + "/StreamingAssets/" + "Log");
                NowTime = DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_");
                fileInfo = new FileInfo(Application.dataPath + "/StreamingAssets/Log/" + NowTime + "_Log.txt");
                txtpath = Application.dataPath + "/StreamingAssets/Log/" + NowTime + "_Log.txt";
                //设置Log文件输出地址
                FileWriter = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
                encoding = new UTF8Encoding();
                mstartTime= DateTime.Now;
                Application.logMessageReceived += LogCallback;
            }
        }
    }


    void deleteDirs(DirectoryInfo dirs)
    {
        if (dirs == null || (!dirs.Exists))
        {
            return;
        }

        DirectoryInfo[] subDir = dirs.GetDirectories();
        if (subDir != null)
        {
            for (int i = 0; i < subDir.Length; i++)
            {
                if (subDir[i] != null)
                {
                    deleteDirs(subDir[i]);
                }
            }
            subDir = null;
        }

        FileInfo[] files = dirs.GetFiles();
        if (files != null)
        {
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i] != null)
                {
                    Debug.Log("删除文件:" + files[i].FullName + "__over");
                    files[i].Delete();
                    files[i] = null;
                }
            }
            files = null;
        }

        Debug.Log("删除文件夹:" + dirs.FullName + "__over");
        dirs.Delete();
    }


    /// <summary>
    ///     替代Debug.log写入Log信息
    /// </summary>
    /// <param name="_log"></param>
    /// <param name="con"></param>
    public static void Log(object _log)
    {

        if ((_LogDisplay == false) && (_AllDisplay == false))
        {

            if (_LogData)
                Debug.Log(_log);
            if (IsIDE == false)
            {
                try
                {
                    var mendTime = DateTime.Now;
                    ts1 = mendTime - mstartTime;
                   
                    if (int.Parse(ts1.Minutes.ToString()) > 720) {
                        //12小时后点击,会自动清除logo日志,720分钟  12小时
                        StreamWriter write = new StreamWriter(txtpath);
                        write.Write("");
                        write.Close();
                    }
                    var trace = new StackTrace(); //获取调用类信息
                    var ClassName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
                    var WayName = trace.GetFrame(1).GetMethod().Name;
                    var log = DateTime.Now + " " + "[" + ClassName + "." + WayName + "]" + " " + ":" + " " + _log +
                              Environment.NewLine;
                    FileWriter.Write(encoding.GetBytes(log), 0, encoding.GetByteCount(log));
                }
                catch (Exception)
                {
                    Debug.Log("请检测是否调用了Console.LogStart方法,或者关闭控制台Log写入与所有数据写入项");
                }

            }
        }
        else
        {
            Debug.Log("请检测是否调用了Console.LogStart方法,或者关闭控制台Log写入与所有数据写入项");
        }
    }

    private void LogCallback(string condition, string stackTrace, LogType type) //写入控制台数据
    {
        string content = null;
        if (_AllDisplay == false)
        {
            if (type.ToString() == "Warning")
                if (_WarningDisplay == false)
                {
                    condition = "";
                    stackTrace = "";
                    content = "";
                }
                else
                {
                    content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " +
                              condition +
                              Environment.NewLine;
                }

            if (type.ToString() == "Log")
                if (_LogDisplay == false)
                {
                    condition = "";
                    stackTrace = "";
                    content = "";
                }
                else
                {
                    content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " +
                              condition +
                              Environment.NewLine;
                }
            if (type.ToString() == "Exception")
                content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " + condition +
                          Environment.NewLine;
        }
        else
        {
            content = DateTime.Now + " " + "[" + type + "]" + "[" + stackTrace + "]" + " " + ":" + " " + condition +
                      Environment.NewLine;
        }
        FileWriter.Write(encoding.GetBytes(content), 0, encoding.GetByteCount(content));
        FileWriter.Flush();
    }

    private void OnDestroy() //关闭写入
    {
        if ((FileWriter != null) && (IsIDE == false))
        {
            FileWriter.Close();
            Application.RegisterLogCallback(null);
        }
    }
}

 

 

//使用的时候,将write.cs 挂载到Gameobject上面 ,start函数里面开启日志就可以

void start(){

//开启Log日志
        Write.console.LogStart(true, false , false , true);

 

}

//打日志   Write.Log("" );

转载修改 GitHub:https://github.com/baishuisr1/Unity-Save-the-log

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值