Skip to content

Instantly share code, notes, and snippets.

@toughrogrammer
Last active June 22, 2020 13:54
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 toughrogrammer/9c1bdfacd3334d6a9ed8 to your computer and use it in GitHub Desktop.
Save toughrogrammer/9c1bdfacd3334d6a9ed8 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.IO;
public class Logger : MonoBehaviour
{
StreamWriter _writer;
public void Prepare()
{
#if UNITY_EDITOR
if (_writer == null) {
_writer = new StreamWriter ( File.Create(@"mylog.txt") );
}
#endif
}
void OnEnable ()
{
Application.RegisterLogCallback (HandleLog);
}
void OnDisable ()
{
Application.RegisterLogCallback (null);
}
void OnApplicationQuit ()
{
if (_writer == null) {
return;
}
_writer.Close ();
}
void HandleLog (string logString, string stackTrace, LogType type)
{
if (_writer == null) {
return;
}
_writer.WriteLine (logString);
_writer.WriteLine (stackTrace);
_writer.WriteLine ();
_writer.Flush ();
}
//
// singleton pattern
//
private static Logger _instance;
private static GameObject _container;
public static Logger Instance {
get {
_instance = GameObject.FindObjectOfType (typeof(Logger)) as Logger;
if (_instance == null) {
_container = new GameObject ("LogMaster");
_instance = _container.AddComponent (typeof(Logger)) as Logger;
}
return _instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment