Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created January 22, 2022 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AldeRoberge/a58a6efa81fb284beac3610566a65421 to your computer and use it in GitHub Desktop.
Save AldeRoberge/a58a6efa81fb284beac3610566a65421 to your computer and use it in GitHub Desktop.
Logs the Unity console on file.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DefaultNamespace
{
using System;
using System.IO;
using System.Text;
using UnityEngine;
namespace Scripts.Utils
{
/// <summary>
/// Logs to a file.
/// </summary>
[DefaultExecutionOrder(-99999)]
public class LogToFile : MonoBehaviour
{
private string filename = "";
private void OnEnable()
{
Application.logMessageReceived += Log;
}
private void OnDisable()
{
Application.logMessageReceived -= Log;
}
private const string LogTag = "[LOG ERROR]";
public void OnApplicationQuit()
{
// Is not in Editor
if (Application.platform != RuntimePlatform.WindowsEditor)
{
Application.OpenURL(filename);
}
}
public void Log(string logString, string stackTrace, LogType type)
{
if (logString.Contains(LogTag))
{
return;
}
if (filename == "")
{
string d = Application.persistentDataPath + "/LOGS";
if (!Directory.Exists(d))
Directory.CreateDirectory(d);
filename = d + "/" + DateTime.UtcNow.ToString("yyyy-MM-d--HH-mm-ss") + ".txt";
Debug.Log("[LogToFile] Will log to '" + filename + "'.");
}
try
{
StringBuilder toAdd = new StringBuilder();
toAdd.AppendLine(logString);
if (type == LogType.Exception || type == LogType.Error)
{
if (!string.IsNullOrWhiteSpace(stackTrace))
{
toAdd.AppendLine("");
toAdd.AppendLine("[BEGIN ERROR STACK TRACE]");
toAdd.AppendLine("[=======================]");
toAdd.AppendLine(stackTrace);
toAdd.AppendLine("[=======================]");
toAdd.AppendLine("[END ERROR STACK TRACE]");
toAdd.AppendLine("");
}
}
else
{
toAdd.AppendLine();
}
File.AppendAllText(filename, toAdd.ToString());
}
catch (Exception e)
{
Debug.LogError(LogTag + " Error on log : " + e);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment