In this lesson, you will learn how to automate the collection of runtime errors and performance metrics by writing them directly to a persistent log file during your build tests.
The Importance of Persistent Logging
When you test a game inside the Unity Editor, you can easily view the Console. However, when you distribute a standalone build to testers, you cannot see their screen or monitor their real-time console output. To solve this, we can use C#’s System.IO namespace to write log messages into a physical file on the user's hard drive. This allows you to "catch" errors even after the game has closed.
Implementing the Log Writer
To capture data, we listen for Unity’s internal log events using Application.logMessageReceived. We then open a file stream and append the error details.
using UnityEngine;
using System.IO;
public class DiagnosticReporter : MonoBehaviour
{
private string logPath;
void Start()
{
// Define a path in the persistent data directory
logPath = Path.Combine(Application.persistentDataPath, "build_log.txt");
Application.logMessageReceived += HandleLog;
}
void HandleLog(string logString, string stackTrace, LogType type)
{
// Append the log entry to the text file
using (StreamWriter writer = new StreamWriter(logPath, true))
{
writer.WriteLine($"[{type}] {System.DateTime.Now}: {logString}");
}
}
}
Why This Matters for Testing
By writing to Application.persistentDataPath, you ensure the file is saved in a location the operating system allows your game to write to, regardless of user permissions.
During your testing phase, you can periodically check this file to identify recurring errors or performance dips that only happen in the build environment. This moves your debugging process away from "I think I saw a crash" toward "I have a timestamped record of the exact Exception." By automating this, you turn every external test session into a reliable data source for your development team.
Key Takeaway: By using Application.logMessageReceived to pipe console output into a persistent text file, you gain the ability to review diagnostic data from any remote build instance long after the test session has concluded.