forked from IvanMurzak/Unity-MCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBufferedFileLogStorage.cs
More file actions
209 lines (189 loc) · 7.63 KB
/
BufferedFileLogStorage.cs
File metadata and controls
209 lines (189 loc) · 7.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*
┌──────────────────────────────────────────────────────────────────┐
│ 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using UnityEngine;
namespace com.IvanMurzak.Unity.MCP
{
using ILogger = Microsoft.Extensions.Logging.ILogger;
public class BufferedFileLogStorage : FileLogStorage
{
protected readonly int _flushEntriesThreshold;
protected readonly LogEntry[] _logEntriesBuffer;
protected int _logEntriesBufferLength;
public BufferedFileLogStorage(
ILogger? logger = null,
int flushEntriesThreshold = 100,
string? cacheFilePath = null,
string? cacheFileName = null,
int fileBufferSize = 4096,
int maxFileSizeMB = DefaultMaxFileSizeMB,
JsonSerializerOptions? jsonOptions = null)
: base(logger, cacheFilePath, cacheFileName, fileBufferSize, maxFileSizeMB, jsonOptions)
{
if (flushEntriesThreshold <= 0)
throw new ArgumentOutOfRangeException(nameof(flushEntriesThreshold), "Flush entries threshold must be greater than zero.");
_flushEntriesThreshold = flushEntriesThreshold;
_logEntriesBuffer = new LogEntry[flushEntriesThreshold];
_logEntriesBufferLength = 0;
}
public override void Flush()
{
if (_isDisposed.Value)
{
_logger.LogWarning("{method} called but already disposed, ignored.",
nameof(Flush));
return;
}
lock (_fileMutex)
{
// Flush buffered entries to file
if (_logEntriesBufferLength > 0)
{
var entriesToFlush = new LogEntry[_logEntriesBufferLength];
Array.Copy(_logEntriesBuffer, entriesToFlush, _logEntriesBufferLength);
base.AppendInternal(entriesToFlush);
_logEntriesBufferLength = 0;
}
fileWriteStream?.Flush();
}
}
public override Task FlushAsync()
{
if (_isDisposed.Value)
{
_logger.LogWarning("{method} called but already disposed, ignored.",
nameof(FlushAsync));
return Task.CompletedTask;
}
lock (_fileMutex)
{
// Flush buffered entries to file
if (_logEntriesBufferLength > 0)
{
var entriesToFlush = new LogEntry[_logEntriesBufferLength];
Array.Copy(_logEntriesBuffer, entriesToFlush, _logEntriesBufferLength);
base.AppendInternal(entriesToFlush);
_logEntriesBufferLength = 0;
}
fileWriteStream?.Flush();
}
return Task.CompletedTask;
}
protected override void AppendInternal(params LogEntry[] entries)
{
if (_isDisposed.Value)
{
_logger.LogWarning("{method} called but already disposed, ignored.",
nameof(AppendInternal));
return;
}
if (_logEntriesBufferLength >= _flushEntriesThreshold)
{
base.AppendInternal(_logEntriesBuffer);
_logEntriesBufferLength = 0;
}
foreach (var entry in entries)
{
_logEntriesBuffer[_logEntriesBufferLength] = entry;
_logEntriesBufferLength++;
if (_logEntriesBufferLength >= _flushEntriesThreshold)
{
base.AppendInternal(_logEntriesBuffer);
_logEntriesBufferLength = 0;
}
}
}
/// <summary>
/// Closes and disposes the current file stream if open. Clears the log cache file.
/// </summary>
public override void Clear()
{
if (_isDisposed.Value)
{
_logger.LogWarning("{method} called but already disposed, ignored.",
nameof(Clear));
return;
}
lock (_fileMutex)
{
fileWriteStream?.Close();
fileWriteStream?.Dispose();
fileWriteStream = null;
_logEntriesBufferLength = 0;
if (File.Exists(filePath))
File.Delete(filePath);
if (File.Exists(filePath))
_logger.LogError("Failed to delete cache file: {file}", filePath);
}
}
public override LogEntry[] Query(
int maxEntries = 100,
LogType? logTypeFilter = null,
bool includeStackTrace = false,
int lastMinutes = 0)
{
if (_isDisposed.Value)
{
_logger.LogWarning("{method} called but already disposed, ignored.",
nameof(Query));
return Array.Empty<LogEntry>();
}
lock (_fileMutex)
{
return QueryInternal(maxEntries, logTypeFilter, includeStackTrace, lastMinutes);
}
}
protected override LogEntry[] QueryInternal(
int maxEntries = 100,
LogType? logTypeFilter = null,
bool includeStackTrace = false,
int lastMinutes = 0)
{
var result = new List<LogEntry>();
var cutoffTime = lastMinutes > 0
? System.DateTime.Now.AddMinutes(-lastMinutes)
: System.DateTime.MinValue;
// 1. Get from buffer (Newest are at the end of buffer)
for (int i = _logEntriesBufferLength - 1; i >= 0; i--)
{
var entry = _logEntriesBuffer[i];
if (logTypeFilter.HasValue && entry.LogType != logTypeFilter.Value)
continue;
if (lastMinutes > 0)
{
if (entry.Timestamp < cutoffTime)
{
return result.AsEnumerable().Reverse().ToArray();
}
}
result.Add(entry);
if (result.Count >= maxEntries)
return result.AsEnumerable().Reverse().ToArray();
}
// 2. Exit if we already have enough entries
var neededLogsCount = maxEntries - result.Count;
if (neededLogsCount <= 0)
return result.AsEnumerable().Reverse().ToArray();
result.Reverse();
// 3. Get from file
var fileEntries = base.QueryInternal(neededLogsCount, logTypeFilter, includeStackTrace, lastMinutes);
result.AddRange(fileEntries);
return result.ToArray();
}
~BufferedFileLogStorage() => Dispose();
}
}