generated from IvanMurzak/Unity-Package-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 68
Add new console log cache to persist log data #264
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jstricklin
wants to merge
62
commits into
main
Choose a base branch
from
persist-console-logs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 51 commits
Commits
Show all changes
62 commits
Select commit
Hold shift + click to select a range
aa37631
add new console log cache to persist log data
jstricklin 165bbc8
update log cache with R3 timer to remove unityeditor dependency and u…
jstricklin f28d16c
update log cache method and variables
jstricklin 324261b
update log cache with simplified file i/o and update log file path
jstricklin c537cde
refactor logcache initialization
jstricklin 882173d
update script to resolve merge conflict
jstricklin 919610d
add test to validate log utils logentry count
jstricklin 8b4f578
remove extraneous logMessageReceived subscription and update test script
jstricklin 88e882b
extract LogWrapper class from LogCache
jstricklin 42a390f
update console log file read with async logic
jstricklin d759244
refactor subscription logic to leverage existing hooks, code cleanup
jstricklin 628cb26
remove unity editor dependency in test script
jstricklin 6e611c6
remove unity editor dependency in test script
jstricklin 44f4315
refactor access to _logEntries, strict variable definitions, and modi…
jstricklin 7d537a6
update test to allow more file write/read time
jstricklin 94c0d51
update restore semaphore to address aync/await issues and add complet…
jstricklin a72402f
update validate log count test
jstricklin 49a101d
disable log count test
jstricklin 34e4e29
disable log retention test
jstricklin 6093dad
update logic to better handle application quit
jstricklin abd1d19
update console log application quit logic
jstricklin be6c4e7
update console log cache init
jstricklin e3348b2
update utils to check for logcache existance before save/load actions…
jstricklin 5375aaf
update log cache instance null check warning to still allow save/load…
jstricklin 326b698
update log cache logic to avoid null instances by instead not setting…
jstricklin 765f27b
Merge branch 'main' into persist-console-logs
IvanMurzak a197e94
Refactor: Simplify LogCache class structure and improve resource mana…
IvanMurzak 10b5a53
Refactor: Simplify JSON serialization in LogCache by removing unneces…
IvanMurzak f576b87
Refactor: Update LogEntry properties to use PascalCase and improve JS…
IvanMurzak 443548e
Refactor: Remove LogTypeString property and update LogEntry usage in …
IvanMurzak c2b59ab
Refactor: Change _logEntries to readonly and update LoadFromFile to e…
IvanMurzak fcf345e
Initial plan
Copilot 791fc18
Update Unity-MCP-Plugin/Assets/root/Runtime/Unity/Logs/LogCache.cs
IvanMurzak 9529eab
Refactor: Change LogCache constructor access modifier from private to…
IvanMurzak edbf664
Merge branch 'fix/persist-console-logs' of https://github.com/IvanMur…
IvanMurzak a4bbb05
Add XML documentation to SaveToFile, LoadFromFile, and HandleQuit met…
Copilot da6b874
Merge pull request #301 from IvanMurzak/copilot/sub-pr-300
IvanMurzak 43ccc65
Refactor LogEntry constructor to use named parameters and improve cla…
IvanMurzak 8d78c80
Refactor LogCache to instance-based usage
IvanMurzak 5faeefb
Merge branch 'main' into persist-console-logs
IvanMurzak da85c8f
Merge pull request #303 from IvanMurzak/update/non-static-log-cache
IvanMurzak fb9b1cf
Merge branch 'persist-console-logs' into fix/persist-console-logs
IvanMurzak 596454d
Merge branch 'main' into persist-console-logs
IvanMurzak bfde02b
Merge branch 'persist-console-logs' into fix/persist-console-logs
IvanMurzak f8a1356
Refactor log caching methods for improved performance and clarity
IvanMurzak beddefd
Enhance logging functionality with main thread checks and improved Lo…
IvanMurzak db82767
Merge branch 'main' into persist-console-logs
IvanMurzak 3a94158
Merge branch 'persist-console-logs' into fix/persist-console-logs
IvanMurzak 6e871ed
Refactor CacheLogEntriesAsync and GetCachedLogEntriesAsync to use asy…
IvanMurzak 350192a
Use 'using' statement for file stream in GetCachedLogEntriesAsync to …
IvanMurzak 8cbf312
Merge pull request #300 from IvanMurzak/fix/persist-console-logs
IvanMurzak 1b521c2
Merge branch 'main' into persist-console-logs
IvanMurzak 9d66ba7
Apply suggestions from code review
IvanMurzak a2496fd
Merge branch 'main' into persist-console-logs
IvanMurzak 8c03b3e
Merge branch 'main' into persist-console-logs
jstricklin 8ef6be1
update cache save to file logic to handle synchronous call on applica…
jstricklin b23750c
update handlequit and add _saving bool to skip cache save subscriptio…
jstricklin a4b96ed
Merge branch 'main' into persist-console-logs
IvanMurzak 2ce8d91
Merge branch 'main' into persist-console-logs
jstricklin 3694856
Merge branch 'main' into persist-console-logs
IvanMurzak b66c529
Merge branch 'main' into persist-console-logs
IvanMurzak 76f9b14
Suppress unused task warnings by discarding results from LogUtils.Han…
IvanMurzak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
147 changes: 147 additions & 0 deletions
147
Unity-MCP-Plugin/Assets/root/Runtime/Unity/Logs/LogCache.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| /* | ||
| ┌──────────────────────────────────────────────────────────────────┐ | ||
| │ Author: Ivan Murzak (https://github.com/IvanMurzak) │ | ||
| │ Repository: GitHub (https://github.com/IvanMurzak/Unity-MCP) │ | ||
| │ Copyright (c) 2025 Ivan Murzak │ | ||
| │ Licensed under the Apache License, Version 2.0. │ | ||
| │ See the LICENSE file in the project root for more information. │ | ||
| └──────────────────────────────────────────────────────────────────┘ | ||
| */ | ||
|
|
||
| #nullable enable | ||
| using System; | ||
| using System.IO; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using com.IvanMurzak.ReflectorNet.Utils; | ||
| using R3; | ||
| using UnityEngine; | ||
|
|
||
| namespace com.IvanMurzak.Unity.MCP | ||
| { | ||
| internal class LogCache : IDisposable | ||
| { | ||
| readonly string _cacheFilePath; | ||
| readonly string _cacheFileName; | ||
| readonly string _cacheFile; | ||
| readonly JsonSerializerOptions _jsonOptions; | ||
| readonly SemaphoreSlim _fileLock = new(1, 1); | ||
| readonly CancellationTokenSource _shutdownCts = new(); | ||
|
|
||
| IDisposable? timerSubscription; | ||
|
|
||
| internal LogCache(string? cacheFilePath = null, string? cacheFileName = null, JsonSerializerOptions? jsonOptions = null) | ||
| { | ||
| if (!MainThread.Instance.IsMainThread) | ||
| throw new System.Exception($"{nameof(LogUtils)} must be initialized on the main thread."); | ||
IvanMurzak marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| _cacheFilePath = cacheFilePath ?? (Application.isEditor | ||
| ? $"{Path.GetDirectoryName(Application.dataPath)}/Temp/mcp-server" | ||
| : $"{Application.persistentDataPath}/Temp/mcp-server"); | ||
|
|
||
| _cacheFileName = cacheFileName ?? (Application.isEditor | ||
| ? "editor-logs.txt" | ||
| : "player-logs.txt"); | ||
|
|
||
| _cacheFile = $"{Path.Combine(_cacheFilePath, _cacheFileName)}"; | ||
| _jsonOptions = jsonOptions ?? new JsonSerializerOptions | ||
| { | ||
| PropertyNameCaseInsensitive = true, | ||
| WriteIndented = false, | ||
| }; | ||
|
|
||
| timerSubscription = Observable.Timer( | ||
| TimeSpan.FromSeconds(1), | ||
| TimeSpan.FromSeconds(1) | ||
| ) | ||
| .Subscribe(x => | ||
| { | ||
| if (!_shutdownCts.IsCancellationRequested) | ||
| Task.Run(HandleLogCache, _shutdownCts.Token); | ||
| }); | ||
jstricklin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| public async Task HandleQuit() | ||
| { | ||
| if (!_shutdownCts.IsCancellationRequested) | ||
| _shutdownCts.Cancel(); | ||
| timerSubscription?.Dispose(); | ||
| await HandleLogCache(); | ||
| } | ||
|
|
||
| public async Task HandleLogCache() | ||
| { | ||
| if (LogUtils.LogEntries > 0) | ||
| { | ||
| var logs = LogUtils.GetAllLogs(); | ||
| await CacheLogEntriesAsync(logs); | ||
| } | ||
| } | ||
|
|
||
| public Task CacheLogEntriesAsync(LogEntry[] entries) | ||
| { | ||
| return Task.Run(async () => | ||
| { | ||
| await _fileLock.WaitAsync(); | ||
| try | ||
| { | ||
| var data = new LogWrapper { Entries = entries }; | ||
|
|
||
| if (!Directory.Exists(_cacheFilePath)) | ||
| Directory.CreateDirectory(_cacheFilePath); | ||
|
|
||
| // Stream JSON directly to file without creating entire JSON string in memory | ||
| var tempFile = _cacheFile + ".tmp"; | ||
| using (var fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) | ||
| { | ||
| await System.Text.Json.JsonSerializer.SerializeAsync(fileStream, data, _jsonOptions); | ||
| await fileStream.FlushAsync(); | ||
| } | ||
|
|
||
| // Atomic file replacement | ||
| if (File.Exists(_cacheFile)) | ||
| File.Delete(_cacheFile); | ||
| File.Move(tempFile, _cacheFile); | ||
| } | ||
| finally | ||
| { | ||
| _fileLock.Release(); | ||
| } | ||
| }); | ||
| } | ||
| public Task<LogWrapper?> GetCachedLogEntriesAsync() | ||
| { | ||
| return Task.Run(async () => | ||
| { | ||
| await _fileLock.WaitAsync(); | ||
| try | ||
| { | ||
| if (!File.Exists(_cacheFile)) | ||
| return null; | ||
|
|
||
| using var fileStream = File.OpenRead(_cacheFile); | ||
| return await System.Text.Json.JsonSerializer.DeserializeAsync<LogWrapper>(fileStream, _jsonOptions); | ||
| } | ||
| finally | ||
| { | ||
| _fileLock.Release(); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| timerSubscription?.Dispose(); | ||
| timerSubscription = null; | ||
|
|
||
| if (!_shutdownCts.IsCancellationRequested) | ||
| _shutdownCts.Cancel(); | ||
| _shutdownCts.Dispose(); | ||
|
|
||
| _fileLock.Dispose(); | ||
| } | ||
|
|
||
| ~LogCache() => Dispose(); | ||
IvanMurzak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
11 changes: 11 additions & 0 deletions
11
Unity-MCP-Plugin/Assets/root/Runtime/Unity/Logs/LogCache.cs.meta
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.