Logger for Unity3d that works great with MonoDevelop

I want to write a central log class for a Unity3d project. Its pretty straight forward if I was to only print console logs. I would like it to look something like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Consider this class is a Singleton, and is available to all other classes. 
//I'm leaving the generic inheritance from something like Singleton<Logger> for simplicity

public class Logger : MonoBehaviour 
{
    public enum LogLevel
    {
        Verbose,
        Debug,
        Warn,
        Error
    }

    public bool _enableLogs;

    public LogLevel _logLevel;

    public void Log(LogLevel logType, string msg)
    {
        if (!_enableLogs)
            return;

        // some logic to filter out messages below this "_logLevel".

        // Log the msg to console.
        Debug.Log (msg);
    }
}

      

Usually when you double-click a log message, it will take you to that line of code in the MonoDevelop. How can I change my code so that it links to the line of code that generates it, for example in a regular logger? Any help is appreciated.

+3


source to share


2 answers


Filter by LogType, analyze the stack trace, and switch to the editor if the source file is found. It's an editor-loaded class, so it only works there, of course.



using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class ExceptionCatcher
{
    private static readonly Regex StackTraceRegex = new Regex(@"\(at (.*):([0-9]+)\)");

    static ExceptionCatcher()
    {
        // Handle logs
        Application.logMessageReceived += OnLogMessageReceived;
    }

    private static void OnLogMessageReceived(string condition, string stackTrace, LogType type)
    {
        // Check if stack trace has file name and line number
        var matches = StackTraceRegex.Matches(stackTrace);
        foreach (Match match in matches)
        {
            // Get full path file name or VS will open new window
            string filePath = Path.GetDirectoryName(Application.dataPath) + "/" + match.Groups[1].Value;
            int lineNumber = Convert.ToInt32(match.Groups[2].Value);

            // If file exists
            if (File.Exists(filePath))
            {
                // Pause editor
                Debug.Break();

                // Switch to code editor
                UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(filePath, lineNumber);
                break;
            }
        }
    }
}

      

0


source


There is a simple solution for what you want: compile your logger to a .DLL and include that .DLL in your project. Now, clicking on the log messages will take you to the right place.



I'm not sure why this works, but it has been known to work for a long time (we also have our own log that works like this).

0


source







All Articles