Context object on logs

I know there is an event I can listen to in order to handle log messages

Application.logMessageReceived

But it uses this delegate

public delegate void LogCallback(string condition, string stackTrace, [URL='https://docs.unity3d.com/ScriptReference/LogType.html']LogType[/URL] type);

Which is missing the “Object context” of the logs

Question is: Is there a way to access this context Object?

If you override the Debug.unityLogger.logHandler reference with your own custom implementation of ILogHandler, then you can intercept all of the ILogHandler.LogFormat(LogType logType, Object context, string format, params object[ ] args) calls. Note, that logs will no longer reach the console unless your custom ILogHandler continues to forward them onto the default Unity logger that was originally assigned to Debug.unityLogger.logHandler. So, it’s useful to cache a reference to the default logger. I cache that reference automaticallly in a static class like this, so that I have the reference to whatever was assigned there when I hit play, at a time when it’s unlikely any other code has changed the default reference. My code always sets Debug.unityLogger.logHandler back to what I cached here when play stops. You could also create an editor only script that uses the [InitializeOnLoad] attribute to cache the default Unity logger as soon as you open Unity. And you could perform a null check before overriding the cached reference again, since the purpose here is just to cache the default logger once, as early as possible. But, remember that [InitializeOnLoad] only works in the editor, so you still also need the [RuntimeInitializeOnLoadMethod] version for it to work in a build.

public static class UnityLogHandler
    {
        public static ILogHandler Default { get; }

        static UnityLogHandler()
        {
            Default = Debug.unityLogger.logHandler;
        }

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
        private static void Initialize()
        { }
    }
1 Like

You can set a custom log handler on Debug.unityLogger.logHandler, its ILogHandler.LogFormat gets the context object as the second argument.

You probably want to wrap the previous handler and forward all messages to it, otherwise logging to Unity’s Console will stop working.

2 Likes

Thanks @CodeRonnie and @Adrian , I had no idea functionality like this existed!

Thank you very much!

1 Like