Version: 2021.3

ILogHandler

interface in UnityEngine

切换到手册

描述

自定义日志处理程序实现的接口。

ILogHandler 接口,用于简化记录器的单元测试和模拟。

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

public class MyFileLogHandler : ILogHandler { private FileStream m_FileStream; private StreamWriter m_StreamWriter; private ILogHandler m_DefaultLogHandler = Debug.unityLogger.logHandler;

public MyFileLogHandler() { string filePath = Application.persistentDataPath + "/MyLogs.txt";

m_FileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); m_StreamWriter = new StreamWriter(m_FileStream);

// Replace the default debug log handler Debug.unityLogger.logHandler = this; }

public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args) { m_StreamWriter.WriteLine(String.Format(format, args)); m_StreamWriter.Flush(); m_DefaultLogHandler.LogFormat(logType, context, format, args); }

public void LogException(Exception exception, UnityEngine.Object context) { m_DefaultLogHandler.LogException(exception, context); } }

public class MyGameClass : MonoBehaviour { private static ILogger logger = Debug.unityLogger; private static string kTAG = "MyGameTag"; private MyFileLogHandler myFileLogHandler;

void Start() { myFileLogHandler = new MyFileLogHandler();

logger.Log(kTAG, "MyGameClass Start."); } }

公共函数

LogException记录异常消息的 ILogHandler.LogFormat 的变体。
LogFormat记录一条格式化的消息。