核心代码:
public static event LogCallback logMessageReceivedThreaded;
public static event LogCallback logMessageReceived;
------------------------------------------------------------------------------------------
public delegate void LogCallback(string condition, string stackTrace, LogType type);
完整代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class Logger : MonoBehaviour
{
private string outPath;
private void Start()
{
InitLogger();
Debug.Log("11111111111111111111111");
Debug.LogWarning("22222222222222222222222");
Debug.LogError("33333333333333333333333");
}
private void OnEnable()
{
Application.logMessageReceivedThreaded += LogCallBack;
}
private void OnDisable()
{
Application.logMessageReceivedThreaded -= LogCallBack;
}
public void InitLogger()
{
outPath = Application.dataPath + "/outLog.txt";
if (File.Exists(outPath))
{
File.Delete(outPath);
}
Debug.Log(outPath.Replace("/outLog.txt", ""));
if (Directory.Exists(Application.dataPath))
{
FileStream fs = File.Create(outPath);
fs.Close();
Debug.Log("注册回调");
}
else
{
Debug.LogError("文件不存在");
}
}
private void LogCallBack(string condition, string stackTrace, LogType type)
{
Debug.Log("回调执行");
if (File.Exists(outPath))
{
using (StreamWriter sw = File.AppendText(outPath))
{
sw.WriteLine(condition);
sw.WriteLine(stackTrace);
}
}
}
}