Logging

If you have already covered a few of the chapters in this book, you can appreciate how valuable logging is to making sure your game works as expected. In Unity, all log messages are output to the Console unless you create a custom logger that writes to a file or service. We will create a custom logger later in this section. For now though, let's look at the logging options Unity provides us with out of the box, as listed:

  • print: This is the shorthand equivalent to Debug.log.
  • Debug.Log, Debug.LogFormat: This outputs the standard information message in unformatted or formatted text. Messages appear with info icon in the Console window.
  • Debug.LogError, Debug.LogErrorFormat: This outputs unformatted and formatted error messages. Messages appear with an error icon in the Console window.
  • Debug.LogException: This outputs the exception to the console with an error icon.
  • Debug.LogWarning, Debug.LogWarningFormat : This outputs unformatted and formatted warning messages. Messages appear with a warning icon in the Console window.
  • Debug.LogAssertion, Debug.LogFormatAssertion: This outputs unformatted and formatted test assertion messages.

In order to use these logging capabilities, you would add these statements to entry, exit, or other points in a script. The following is an example of Unity script that shows how each of these logging types may be used:

using UnityEngine; 
using System.Collections; 
using System; 
 
public class LoggingExample : MonoBehaviour { 
 
    public GameObject target; 
    public float iterations = 1000; 
    private float start; 
  // Use this for initialization 
  void Start () { 
        Debug.Log("Start"); 
 
        if (target == null) 
        { 
            Debug.LogWarning("target object not set"); 
        } 
 
        if (iterations < 1) 
        { 
            Debug.LogWarningFormat("interations: {0} < 1", iterations); 
        } 
 
        Debug.LogFormat("{0} iterations set", iterations); 
        start = iterations; 
  } 
   
  // Update is called once per frame 
  void Update () { 
        //try/catch used for demo 
        //never use in an update method 
        try 
        { 
            iterations--; 
            Debug.LogFormat("Progress {0}%", (100 - iterations / start * 100)); 
        } 
        catch (Exception ex) 
        { 
            Debug.LogError("Error encountered " + ex.Message); 
            Debug.LogErrorFormat("Error at {0} iterations, msg = {1}", iterations, ex.Message); 
            Debug.LogException(ex); 
        } 
  } 
} 

The LoggingExample class is an example of the use of the various types of logging available in Unity.

In the LoggingExample class, what will happen if the initial iterations is set to 0? What change can you make to get the sample to throw an exception?

Of course, most of the time, outputting log messages to the Console window will be fine, especially in development. However, in other situations, after the game has been deployed, either for testing or commercially, you may still want to track those messages. Fortunately, there is a very easy ability to handle custom log output, as shown in the following class:

using System; 
using System.IO; 
using UnityEngine; 
 
public class CustomLogHandler : MonoBehaviour 
{ 
    public string logFile = "log.txt"; 
    private string rootDirectory = @"Assets/StreamingAssets"; 
    private string filepath; 
    void Awake() 
    { 
        Application.logMessageReceived += Application_logMessageReceived; 
 
#if UNITY_EDITOR 
        filepath = string.Format(rootDirectory + @"/{0}", logFile); 
        if(Directory.Exists(rootDirectory)==false) 
        { 
            Directory.CreateDirectory(rootDirectory); 
        }        
#else 
        // check if file exists in Application.persistentDataPath 
        filepath = string.Format("{0}/{1}", Application.persistentDataPath, logFile); 
#endif 
    } 
 
    private void Application_logMessageReceived(string condition, string stackTrace, LogType type) 
    { 
        var level = type.ToString(); 
        var time = DateTime.Now.ToShortTimeString(); 
        var newLine = Environment.NewLine; 
 
        var log = string.Format("{0}:[{1}]:{2}{3}" 
            , level,time, condition, newLine); 
 
        try 
        { 
            File.AppendAllText(filepath, log); 
        } 
        catch (Exception ex) 
        { 
            var msg = ex.Message; 
        } 
    }  
} 

The CustomLogHandler works by attaching itself to the Application.logMessageReceived event in the Awake method. This event is called whenever content is logged in Unity. The rest of the class is about configuring the correct file path, creating folders if needed, and then formatting output, where the actual logging takes place in the Application_logMessageReceived method. While this class may not be well suited for mobile platforms, it is perfect for tracking log running messages in the editor or on a desktop platform deployment. In the next couple of sections, we will look at how this log handling can be used for debugging and/or to release deployments.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.127.232