1. 程式人生 > >記錄移動端日誌,儲存沙盒目錄

記錄移動端日誌,儲存沙盒目錄

   這個一個簡單日誌了,日誌只要掛在攝像機上,移動端測試時,自動列印系統錯誤日誌到沙盒目錄File底下,也可以在自己想列印的地方使用Log.print(string info)列印。

using UnityEngine;
using System.Collections;
using System.IO;

public class Log : MonoBehaviour
{
    static string path;
    static int line = 0;

    void Start()
    {
        Application.logMessageReceived += SystemLogPrint;
        if(Application.platform==RuntimePlatform.Android)
        path = Application.persistentDataPath + "/LogFile.txt";
        else
            path = Application.dataPath + "/LogFile.txt";
    }
    void SystemLogPrint(string condition, string stackTrace, LogType type)
    {
        print(condition);
    }
    public static void print(string info)
    {
        line++;
         StreamWriter sw;
        //Debug.Log (path);
        if (line == 1)
        {
            sw = new StreamWriter(path, false);
            string fileTitle = "日誌檔案建立的時間  " + System.DateTime.Now.ToString();
            sw.WriteLine(fileTitle);
        }
        else
        {
            sw = new StreamWriter(path, true);
        }

        string lineInfo = line + "\t" + "時刻 " + Time.time + ": ";
        sw.WriteLine(lineInfo);
        sw.WriteLine(info);
        Debug.Log(info);

        sw.Flush();
        sw.Close();
    }

    // Update is called once per frame
    void Update()
    {
        // test
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Log.print("Unity");
        }
    }
}