- Home /
Is there a way to hook to Application.logMessageReceived without having to put a monobehaviour in scene ?
I have an error logger which works fine by hooking to Application.logMessageReceived in Awake() in a script called ErrorLogger.cs that I must place in every scene.
code bellow:
using System;
using System.IO;
using UnityEngine;
public class ErrorLogger : MonoBehaviour
{
const string ERRORS_FILE = "error_logs.txt";
static bool deleteFile = true;
string filePath;
private void Awake()
{
CreateDirectoryPathIfNonExistent(Paths.LOCAL_DATA);
filePath = Paths.LOCAL_DATA.CreatePathFile(ERRORS_FILE);
if (deleteFile)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
deleteFile = false;
}
Application.logMessageReceived += OnUnityLog;
}
void CreateDirectoryPathIfNonExistent(params string[] path)
{
var curPath = path[0];
for (int i = 0; i < path.Length; i++)
{
if (!Directory.Exists(curPath))
{
Directory.CreateDirectory(curPath);
}
if (i + 1 < path.Length)
{
curPath = curPath.CreatePathFolder(path[i + 1]);
}
}
}
void Log(string aMessage)
{
UIConsole.Log(aMessage);
try
{
var time = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss tt");
File.AppendAllText(filePath, $"{time}\n{aMessage}\n");
}
catch (Exception e)
{
UIConsole.Log($"Cannot write error in local data {e.Message}");
}
}
private void OnDisable()
{
Application.logMessageReceived -= OnUnityLog;
}
private void OnUnityLog(string logString, string stackTrace, LogType type)
{
if (type == LogType.Error)
{
Log("ERROR: " + logString + ":" + stackTrace);
}
else if (type == LogType.Exception)
{
Log("EXCEPTION: " + logString + ":" + stackTrace);
}
}
}
The only drawback for this is that I have to place an object with this script attached in every scene in order to catch all exceptions and log them where I want.
I know I can place an object in just one startup scene and call DontDestroyOnLoad so I only have to put this ErrorLogger in just one scene but that also involves more complications and I was wondering if you can somehow hook to unity events outside the Monobehaviour framework, for example, calling a method when application starts or something.
Your answer
Follow this Question
Related Questions
Custom Inspector: Unity Events 2 Answers
How to pass UnityEvent object as method Parameter 0 Answers
Low frame rate leads to low UI event response. 0 Answers
Should I use EventTriggers as a component or as a superclass for another component? 0 Answers
how do i send additional data with a standard event 1 Answer