Log system reconstruction of Unity3d

Posted by RussellReal on Wed, 15 Apr 2020 19:52:49 +0200

Editor's note

Since the Log system of Unity3d is to be rewritten, it is changed to the user-defined mode, and the content method displayed according to Log4j is used

Log of Unity3d

In general, write log entry code in Unity3d

Debug.Log("hello message");

In UnityEditor and UnityEngine, in addition to printing message s, stack information will also be printed. The performance is low. According to the experience, printing a large number of logs on the client side will seriously reduce the rendering performance.

Debug principle of Unity3d

Principle analysis

Check the implementation of Debug.Log in Rider, and we can see the following

public static void Log(object message)
{
    Debug.unityLogger.Log(LogType.Log, message);
}

We can see that the essence is to call Debug.unityLogger

public static ILogger unityLogger
{
    get
    {
        return Debug.s_Logger;
    }
}

unityLogger actually calls debug.s'logger, and the implementation of s'logger is defined below

internal static ILogger s_Logger = (ILogger) new Logger((ILogHandler) new DebugLogHandler());

DebugLogHandler is essentially a static method called according to the implementation of each platform of 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);
    }
  }
}

There are only two ways to get there

internal static extern void Internal_Log(LogType level, string msg, [Writable] Object obj);
internal static extern void Internal_LogException(Exception exception, [Writable] Object obj);

Code testing

Debug.unityLogger.Log(LogType.Log,"hello message");

UnityEditor printing

hello message
UnityEngine.Logger:Log(LogType, Object)
InitController:Start() (at Assets/Scripts/Controller/InitController.cs:14)

Conclusion: the problem of reducing stack information printing cannot be solved

Application.

Topics: log4j