编者注
由于要重写Unity3d的Log系统,变更为自定义方式,按照Log4j的显示的内容方法
Unity3d的Log
一般在Unity3d中编写日志入下代码
Debug.Log("hello message");
在UnityEditor和UnityEngine当中除了打印message以外,还会打印堆栈信息。性能低下,根据有经验的人讲解,在客户端打印大量日志,会严重降低渲染性能。
Unity3d的Debug原理
原理分析
在Rider中查看Debug.Log的实现,我们可以看到如下内容
public static void Log(object message)
{
Debug.unityLogger.Log(LogType.Log, message);
}
我们能够了解到,实质是调用了Debug.unityLogger
public static ILogger unityLogger
{
get
{
return Debug.s_Logger;
}
}
unityLogger实质是调用了Debug.s_Logger,而在下面就定义了s_Logger的实现
internal static ILogger s_Logger = (ILogger) new Logger((ILogHandler) new DebugLogHandler());
DebugLogHandler实质是调用的静态方法,根据UnityEngine各个平台的实现进行调用
using System;
using System.Runtime.CompilerServices;
using UnityEngine.Scripting;
namespace UnityEngine
{
internal sealed class DebugLogHandler : ILogHandler
{
[ThreadAndSerializationSafe]
[GeneratedByOldBindingsGenerator]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void Internal_Log(LogType level, string msg, [Writable] Object obj);
[ThreadAndSerializationSafe]
[GeneratedByOldBindingsGenerator]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void Internal_LogException(Exception exception, [Writable] Object obj);
public void LogFormat(LogType logType, Object context, string format, params object[] args)
{
DebugLogHandler.Internal_Log(logType, string.Format(format, args), context);
}
public void LogException(Exception exception, Object context)
{
DebugLogHandler.Internal_LogException(exception, context);
}
}
}
最终实现仅仅只有两个方法
internal static extern void Internal_Log(LogType level, string msg, [Writable] Object obj);
internal static extern void Internal_LogException(Exception exception, [Writable] Object obj);
代码测试
Debug.unityLogger.Log(LogType.Log,"hello message");
UnityEditor打印
hello message
UnityEngine.Logger:Log(LogTy