Unity3d的Log系统重构

编者注

由于要重写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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值