Unity -- log printing tool

Posted by franzy_pan on Fri, 28 Jan 2022 19:53:14 +0100

1, Log tool function

To encapsulate the Debug class, you need to implement the following functions:

1. Control whether all logs are printed;

2. In addition to Log, Warning and Error, give more Log types (different colors);

3. Format and print the log;

4. Indefinite parameters, automatically spliced into a string;

5. Upload logs to the server;

2, Logger class

1. Control log printing

Encapsulate the Log method in Debug;

Use static methods to declare static fields and control whether log, warning and error are printed;

The Log method in the Debug source code has two overloads;

The second parameter, context, can be transferred to the preform in GameObject, Hierarchy or Project window. Double clicking the Console log will directly jump to the selected incoming game object;

We can merge this method, and the second parameter is null by default;

2. Color printing

Print different colors using Rich text

string.Format("<color={0}>{1}</color>",color,obj);
3. Multi parameter splicing

FMT which used Go language before Println has a function that is easy to use, continuously transmitting multiple parameters and automatically splicing;

public static void Log(params object[] messags)
{
    if (!s_debugLogEnable) return;

    string message = string.Empty;
    foreach (var it in messags)
    {
        message += it.ToString();
    }

    Debug.Log(message, null);
}

//call
Logger.Log("Net error:",error,"msgId:",msgId);
4. Format printing

Format print package original debug Logformat method;

public static void LogFormat(string format, params object[] args)
{
    if (!s_debugLogEnable) return;
    Debug.LogFormat(format, args);
}

3, LoggerMgr class

Inherit the singleton of MonoBehavior;

Initialize the three fields in the Logger that control printing;

The Application class has the event LogMessageReceived triggered by receiving the log message;

Monitor this event; If the log switch is off, return;

if (isOpenLog)
{
    Logger.s_debugLogEnable = true;
    Logger.s_warningLogEnable = true;
    Logger.s_errorLogEnable = true;          
}

Application.logMessageReceived += (string condition, string stackTrace, LogType type) =>
{
    switch (type)
    {
        case LogType.Log:
            {
                if (!Logger.s_debugLogEnable) return;
            }
            break;
        case LogType.Warning:
            {
                if (!Logger.s_warningLogEnable) return;
            }
            break;
        case LogType.Error:
            {
                if (!Logger.s_errorLogEnable) return;
            }
            break;
    }
};

4, Upload log

Initialize and upload log information in LoggerMgr;

The method is written in the logger and called at LoggerMgr;

public static void Init(string url)
{
    LogUploader.SetUploadUrl(url);
    // date
    var t = System.DateTime.Now.ToString("yyyyMMddhhmmss");
    s_logFileSavePath = string.Format("{0}/output_{1}.log", Application.persistentDataPath, t);
    Application.logMessageReceived += OnLogCallBack;
}

The OnLogCallBack method stores the log and stack information into files and waits for uploading;

private static void OnLogCallBack(string condition, string stackTrace, LogType type)
{
    s_logStr.Append(condition);
    s_logStr.Append("\n");
    s_logStr.Append(stackTrace);
    s_logStr.Append("\n");

    if (s_logStr.Length <= 0) return;
    if (!File.Exists(s_logFileSavePath))
    {
        var fs = File.Create(s_logFileSavePath);
        fs.Close();
    }
    using (var sw = File.AppendText(s_logFileSavePath))
    {
        sw.WriteLine(s_logStr.ToString());
    }
    s_logStr.Remove(0, s_logStr.Length);
}

LogUploader class

Open the log file of collaborative process upload;

public static void StartUploadLog(string logFilePath, string desc)
{
    if (LOG_UPLOAD_URL == string.Empty)
        return;

    var go = new GameObject("LogUploader");
    var bhv = go.AddComponent<LogUploader>();
    bhv.StartCoroutine(bhv.UploadLog(logFilePath, LOG_UPLOAD_URL, desc));
}

The above methods are also encapsulated in the Logger class, and all logs are printed through the Logger;

public static void UploadLog(string desc)
{
    LogUploader.StartUploadLog(s_logFileSavePath, desc);
}

5, Log double click traceability

There is a big problem with the above code. Now we will not go back to the place where we call Logger by double clicking, but only jump to the Logger class to call Debug.. The place of log;

There is a very simple solution. Compile the above code into dll;

In addition, you can find the source code and decide the turning position by yourself;

The specific method is to obtain the log stack information through reflection, and filter the position to jump according to the stack information path returned by the Logger class;

Jump to the corresponding position through the method provided by the official;

UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(string filename, int line);

6, Call

void Start()
{
    Logger.Log("aaaa");
    Logger.LogFormat("{0}===={1}",111,0.232);
    Logger.LogGreen("bbbb");
    Logger.LogError("log error");
    Logger.Log("aa", 13, "fff",16,"sfddf",64654);
    Logger.UploadLog("NetWork LogTest");
}

Tool class Download

Topics: Unity