Unity 日志保存文本

Untiy 提供了日志回调事件 Application.logMessageReceivedThreaded

监听这个事件,即可把文件保存文本文件了。

using UnityEngine;
using System.IO;
using System.Text;
using System;

public class LogManager : MonoBehavior
{
    /// 
    /// 日志流
    /// 
    private StreamWriter logStream;

    private readonly object _keyObj = new object();

    private string logPath
    {
        get
        {
            return Application.persistentDataPath + "/game.log";
        }
    }

    private void Awake()
    {
        Application.logMessageReceivedThreaded += HandleLog;
    }

    private void Start()
    {
        try
        {
            logStream = new StreamWriter(logPath, false, Encoding.UTF8);
        }
        catch { }

    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        Application.logMessageReceivedThreaded -= HandleLog;
    }

    private readonly StringBuilder logBuilder = new StringBuilder();

    private void HandleLog(string logString, string stackTrace, LogType type)
    {
        if (logStream == null)
            return;

        lock (_keyObj)
        {
            logBuilder.Clear();
            logBuilder.Append(string.Format("{0}[{1}]:{2}   trace:{3}",DateTime.Now.ToString("[yyyy-HH-dd mm:hh:ss]"),type,logString,stackTrace));
            logStream.WriteLine(logBuilder.ToString());
            logStream.Flush();
        }

    }

}

你可能感兴趣的:(unity笔记)