Skip to content

Commit fb1e284

Browse files
committed
Fixed the Console Logs behaviour and moved the logs state logic to ConsoleLogsService
1 parent c83c528 commit fb1e284

File tree

6 files changed

+235
-120
lines changed

6 files changed

+235
-120
lines changed
Lines changed: 7 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Reflection;
4-
using UnityEngine;
51
using Newtonsoft.Json.Linq;
6-
using UnityEditor;
2+
using McpUnity.Services;
73

84
namespace McpUnity.Resources
95
{
@@ -12,36 +8,15 @@ namespace McpUnity.Resources
128
/// </summary>
139
public class GetConsoleLogsResource : McpResourceBase
1410
{
15-
// Structure to store log information
16-
private class LogEntry
17-
{
18-
public string Message { get; set; }
19-
public string StackTrace { get; set; }
20-
public LogType Type { get; set; }
21-
public DateTime Timestamp { get; set; }
22-
}
23-
24-
// Collection to store all log messages
25-
private readonly List<LogEntry> _logEntries = new List<LogEntry>();
11+
private readonly IConsoleLogsService _consoleLogsService;
2612

27-
public GetConsoleLogsResource()
13+
public GetConsoleLogsResource(IConsoleLogsService consoleLogsService)
2814
{
2915
Name = "get_console_logs";
3016
Description = "Retrieves all logs from the Unity console";
3117
Uri = "unity://logs";
3218

33-
// Register for log messages
34-
Application.logMessageReceived += OnLogMessageReceived;
35-
36-
#if UNITY_6000_0_OR_NEWER
37-
// Unity 6 specific implementation
38-
ConsoleWindowUtility.consoleLogsChanged += OnConsoleCountChanged;
39-
#else
40-
// Unity 2022.3 implementation using reflection
41-
EditorApplication.update += CheckConsoleClearViaReflection;
42-
#endif
43-
44-
Debug.Log("[MCP Unity] Console logs resource initialized");
19+
_consoleLogsService = consoleLogsService;
4520
}
4621

4722
/// <summary>
@@ -51,22 +26,8 @@ public GetConsoleLogsResource()
5126
/// <returns>A JObject containing the list of logs</returns>
5227
public override JObject Fetch(JObject parameters)
5328
{
54-
// Convert log entries to a JSON array
55-
JArray logsArray = new JArray();
56-
57-
lock (_logEntries)
58-
{
59-
foreach (var entry in _logEntries)
60-
{
61-
logsArray.Add(new JObject
62-
{
63-
["message"] = entry.Message,
64-
["stackTrace"] = entry.StackTrace,
65-
["type"] = entry.Type.ToString(),
66-
["timestamp"] = entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
67-
});
68-
}
69-
}
29+
// Get logs from the service
30+
JArray logsArray = _consoleLogsService.GetAllLogsAsJson();
7031

7132
// Create the response
7233
return new JObject
@@ -77,77 +38,6 @@ public override JObject Fetch(JObject parameters)
7738
};
7839
}
7940

80-
/// <summary>
81-
/// Check if console was cleared using reflection (for Unity 2022.3)
82-
/// </summary>
83-
private void CheckConsoleClearViaReflection()
84-
{
85-
try
86-
{
87-
// Get current log counts using LogEntries (internal Unity API)
88-
var logEntriesType = Type.GetType("UnityEditor.LogEntries,UnityEditor");
89-
if (logEntriesType == null) return;
90-
91-
var getCountMethod = logEntriesType.GetMethod("GetCount",
92-
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
93-
if (getCountMethod == null) return;
94-
95-
int currentTotalCount = (int)getCountMethod.Invoke(null, null);
96-
97-
// If we had logs before, but now we don't, console was likely cleared
98-
if (currentTotalCount == 0 && _logEntries.Count > 0)
99-
{
100-
ClearLogs();
101-
}
102-
}
103-
catch (Exception ex)
104-
{
105-
// Just log the error but don't break functionality
106-
Debug.LogError($"[MCP Unity] Error checking console clear: {ex.Message}");
107-
}
108-
}
109-
110-
/// <summary>
111-
/// Callback for when a log message is received
112-
/// </summary>
113-
/// <param name="logString">The log message</param>
114-
/// <param name="stackTrace">The stack trace</param>
115-
/// <param name="type">The log type</param>
116-
private void OnLogMessageReceived(string logString, string stackTrace, LogType type)
117-
{
118-
// Add the log entry to our collection
119-
_logEntries.Add(new LogEntry
120-
{
121-
Message = logString,
122-
StackTrace = stackTrace,
123-
Type = type,
124-
Timestamp = DateTime.Now
125-
});
126-
}
127-
128-
#if UNITY_6000_0_OR_NEWER
129-
/// <summary>
130-
/// Called when the console logs count changes
131-
/// </summary>
132-
private void OnConsoleCountChanged()
133-
{
134-
ConsoleWindowUtility.GetConsoleLogCounts(out int error, out int warning, out int log);
135-
if (error == 0 && warning == 0 && log == 0 && _logEntries.Count > 0)
136-
{
137-
ClearLogs();
138-
}
139-
}
140-
#endif
141-
142-
/// <summary>
143-
/// Clear all stored log entries
144-
/// </summary>
145-
private void ClearLogs()
146-
{
147-
lock (_logEntries)
148-
{
149-
_logEntries.Clear();
150-
}
151-
}
41+
15242
}
15343
}

Editor/Services/ConsoleLogsService.cs

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Reflection;
4+
using Newtonsoft.Json.Linq;
5+
using UnityEditor;
6+
using UnityEngine;
7+
8+
namespace McpUnity.Services
9+
{
10+
/// <summary>
11+
/// Service for managing Unity console logs
12+
/// </summary>
13+
public class ConsoleLogsService : IConsoleLogsService
14+
{
15+
// Structure to store log information
16+
private class LogEntry
17+
{
18+
public string Message { get; set; }
19+
public string StackTrace { get; set; }
20+
public LogType Type { get; set; }
21+
public DateTime Timestamp { get; set; }
22+
}
23+
24+
// Collection to store all log messages
25+
private readonly List<LogEntry> _logEntries = new List<LogEntry>();
26+
27+
/// <summary>
28+
/// Constructor
29+
/// </summary>
30+
public ConsoleLogsService()
31+
{
32+
StartListening();
33+
}
34+
35+
/// <summary>
36+
/// Start listening for logs
37+
/// </summary>
38+
public void StartListening()
39+
{
40+
// Register for log messages
41+
Application.logMessageReceived += OnLogMessageReceived;
42+
43+
#if UNITY_6000_0_OR_NEWER
44+
// Unity 6 specific implementation
45+
ConsoleWindowUtility.consoleLogsChanged += OnConsoleCountChanged;
46+
#else
47+
// Unity 2022.3 implementation using reflection
48+
EditorApplication.update += CheckConsoleClearViaReflection;
49+
#endif
50+
}
51+
52+
/// <summary>
53+
/// Stop listening for logs
54+
/// </summary>
55+
public void StopListening()
56+
{
57+
// Unregister from log messages
58+
Application.logMessageReceived -= OnLogMessageReceived;
59+
60+
#if UNITY_6000_0_OR_NEWER
61+
// Unity 6 specific implementation
62+
ConsoleWindowUtility.consoleLogsChanged -= OnConsoleCountChanged;
63+
#else
64+
// Unity 2022.3 implementation using reflection
65+
EditorApplication.update -= CheckConsoleClearViaReflection;
66+
#endif
67+
68+
Debug.Log("[MCP Unity] Console logs service shutdown");
69+
}
70+
71+
/// <summary>
72+
/// Get all logs as a JSON array
73+
/// </summary>
74+
/// <returns>JArray containing all logs</returns>
75+
public JArray GetAllLogsAsJson()
76+
{
77+
// Convert log entries to a JSON array
78+
JArray logsArray = new JArray();
79+
80+
lock (_logEntries)
81+
{
82+
foreach (var entry in _logEntries)
83+
{
84+
logsArray.Add(new JObject
85+
{
86+
["message"] = entry.Message,
87+
["stackTrace"] = entry.StackTrace,
88+
["type"] = entry.Type.ToString(),
89+
["timestamp"] = entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
90+
});
91+
}
92+
}
93+
94+
return logsArray;
95+
}
96+
97+
/// <summary>
98+
/// Clear all stored logs
99+
/// </summary>
100+
private void ClearLogs()
101+
{
102+
lock (_logEntries)
103+
{
104+
_logEntries.Clear();
105+
}
106+
}
107+
108+
/// <summary>
109+
/// Check if console was cleared using reflection (for Unity 2022.3)
110+
/// </summary>
111+
private void CheckConsoleClearViaReflection()
112+
{
113+
try
114+
{
115+
// Get current log counts using LogEntries (internal Unity API)
116+
var logEntriesType = Type.GetType("UnityEditor.LogEntries,UnityEditor");
117+
if (logEntriesType == null) return;
118+
119+
var getCountMethod = logEntriesType.GetMethod("GetCount",
120+
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
121+
if (getCountMethod == null) return;
122+
123+
int currentTotalCount = (int)getCountMethod.Invoke(null, null);
124+
125+
// If we had logs before, but now we don't, console was likely cleared
126+
if (currentTotalCount == 0 && _logEntries.Count > 0)
127+
{
128+
ClearLogs();
129+
}
130+
}
131+
catch (Exception ex)
132+
{
133+
// Just log the error but don't break functionality
134+
Debug.LogError($"[MCP Unity] Error checking console clear: {ex.Message}");
135+
}
136+
}
137+
138+
/// <summary>
139+
/// Callback for when a log message is received
140+
/// </summary>
141+
/// <param name="logString">The log message</param>
142+
/// <param name="stackTrace">The stack trace</param>
143+
/// <param name="type">The log type</param>
144+
private void OnLogMessageReceived(string logString, string stackTrace, LogType type)
145+
{
146+
// Add the log entry to our collection
147+
_logEntries.Add(new LogEntry
148+
{
149+
Message = logString,
150+
StackTrace = stackTrace,
151+
Type = type,
152+
Timestamp = DateTime.Now
153+
});
154+
}
155+
156+
#if UNITY_6000_0_OR_NEWER
157+
/// <summary>
158+
/// Called when the console logs count changes
159+
/// </summary>
160+
private void OnConsoleCountChanged()
161+
{
162+
ConsoleWindowUtility.GetConsoleLogCounts(out int error, out int warning, out int log);
163+
if (error == 0 && warning == 0 && log == 0 && _logEntries.Count > 0)
164+
{
165+
ClearLogs();
166+
}
167+
}
168+
#endif
169+
}
170+
}

Editor/Services/ConsoleLogsService.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using Newtonsoft.Json.Linq;
4+
using UnityEngine;
5+
6+
namespace McpUnity.Services
7+
{
8+
/// <summary>
9+
/// Interface for the console logs service
10+
/// </summary>
11+
public interface IConsoleLogsService
12+
{
13+
/// <summary>
14+
/// Get all logs as a JSON array
15+
/// </summary>
16+
/// <returns>JArray containing all logs</returns>
17+
JArray GetAllLogsAsJson();
18+
19+
/// <summary>
20+
/// Start listening for logs
21+
/// </summary>
22+
void StartListening();
23+
24+
/// <summary>
25+
/// Stop listening for logs
26+
/// </summary>
27+
void StopListening();
28+
}
29+
}

Editor/Services/IConsoleLogsService.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)