using UnityEngine;
using System.Collections.Generic;
namespace LocalMcp.UnityServer
{
/// <summary>
/// Global log capture system that persists across HTTP requests
/// </summary>
public class GlobalLogCapture
{
private static GlobalLogCapture _instance;
private List<LogEntry> logHistory = new List<LogEntry>();
private const int MAX_LOG_HISTORY = 1000;
public static GlobalLogCapture Instance
{
get
{
if (_instance == null)
{
_instance = new GlobalLogCapture();
_instance.Initialize();
}
return _instance;
}
}
private GlobalLogCapture()
{
// Private constructor for singleton
}
private void Initialize()
{
Application.logMessageReceived += HandleLog;
}
public void Cleanup()
{
Application.logMessageReceived -= HandleLog;
}
private void HandleLog(string logString, string stackTrace, LogType type)
{
lock (logHistory)
{
var entry = new LogEntry
{
message = logString,
stackTrace = stackTrace,
type = type,
timestamp = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
};
logHistory.Add(entry);
// Keep only last MAX_LOG_HISTORY entries
if (logHistory.Count > MAX_LOG_HISTORY)
{
logHistory.RemoveAt(0);
}
}
}
public List<LogEntry> GetLogs(int count, string levelFilter)
{
List<LogEntry> filteredLogs = new List<LogEntry>();
lock (logHistory)
{
// Return logs in reverse order (newest first)
for (int i = logHistory.Count - 1; i >= 0 && filteredLogs.Count < count; i--)
{
var log = logHistory[i];
if (ShouldIncludeLog(log.type, levelFilter))
{
filteredLogs.Add(log);
}
}
}
return filteredLogs;
}
public int GetTotalLogCount()
{
lock (logHistory)
{
return logHistory.Count;
}
}
private bool ShouldIncludeLog(LogType logType, string levelFilter)
{
if (levelFilter == "all" || string.IsNullOrEmpty(levelFilter))
{
return true;
}
string level = levelFilter.ToLower();
switch (logType)
{
case LogType.Error:
case LogType.Exception:
case LogType.Assert:
return level.Contains("error");
case LogType.Warning:
return level.Contains("warning");
case LogType.Log:
return level.Contains("log") || level.Contains("info");
default:
return false;
}
}
}
[System.Serializable]
public class LogEntry
{
public string message;
public string stackTrace;
public LogType type;
public string timestamp;
}
}