Skip to content

Commit 4e4dbf6

Browse files
committed
MirrorInternalLogs: add failsafe for access violation on log file open
1 parent abd9387 commit 4e4dbf6

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/MirrorInternalLogs/MirrorInternalLogsPatcher.cs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,38 @@ private static void InitializeFileLog()
9797
}));
9898
var dir = Path.GetDirectoryName(path);
9999
Directory.CreateDirectory(dir);
100-
writer = new StreamWriter(path, false, Encoding.UTF8) {AutoFlush = true};
100+
if (!TryCreateFile(path, out writer))
101+
{
102+
Logger.LogWarning($"Couldn't create log file because the file is likely in use, skipping mirroring logs...");
103+
return;
104+
}
101105

102106
InternalUnityLogger.OnUnityInternalLog += InternalUnityLoggerOnOnUnityInternalLog;
103107
}
104108

109+
private static bool TryCreateFile(string path, out StreamWriter sw, int max = 50)
110+
{
111+
var dir = Path.GetDirectoryName(path);
112+
var filename = Path.GetFileNameWithoutExtension(path);
113+
var ext = Path.GetExtension(path);
114+
115+
for (var i = 0; i < max; i++)
116+
{
117+
try
118+
{
119+
var filePath = Path.Combine(dir, $"{filename}{(i > 0 ? $"_{i}" : "")}{ext}");
120+
sw = new StreamWriter(filePath, false, Encoding.UTF8) {AutoFlush = true};
121+
return true;
122+
}
123+
catch (Exception)
124+
{
125+
// skip
126+
}
127+
}
128+
sw = null;
129+
return false;
130+
}
131+
105132
private static void InternalUnityLoggerOnOnUnityInternalLog(object sender, UnityLogEventArgs e)
106133
{
107134
try

0 commit comments

Comments
 (0)