纳金网

标题: 对5.3.3的Debug.logger的理解 [打印本页]

作者: 雅雅    时间: 2016-4-20 00:19
标题: 对5.3.3的Debug.logger的理解

已知public static ILogger logger(Debug会自己Get default debug logger给它赋值)
logger Implements interfaces: ILogger, ILogHandle(Initializes a new instance of the Logger)
其中ILogger Implements interfaces: ILogHandle(并且ILogger 包含一个ILogHandle属性)
可推测在执行类似Debug.Log的Api时会收到消息事件执行logger的ILogHandle,在ILogHandle中往下执行ILogger。
我们可以自定义继承ILogHandle接口的类替换logger的ILogHandle从而达到对日志的加工处理(如日志存档,发送等)
截取消息事件也可用Application中的委托处理。
官方ILogHandle示列(Interface for custom log handler implementation)
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.IO;
  4. using System;

  5. public class MyFileLogHandler : ILogHandler
  6. {
  7.     private FileStream m_FileStream;
  8.     private StreamWriter m_StreamWriter;
  9.     private ILogHandler m_DefaultLogHandler = Debug.logger.logHandler;

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

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

  15.         // Replace the default debug log handler
  16.         Debug.logger.logHandler = this;
  17.     }

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

  24.     public void LogException (Exception exception, UnityEngine.Object context)
  25.     {
  26.         m_DefaultLogHandler.LogException (exception, context);
  27.     }
  28. }

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

  33.     void Start() {
  34.         myFileLogHandler = new MyFileLogHandler();

  35.         logger.Log(kTAG, "MyGameClass Start.");
  36.     }
  37. }
复制代码





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5