From d91c8a68c91ad0df7b4292f6e78761c225cfc166 Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 17 Jul 2024 16:58:02 +0900 Subject: [PATCH] Fix ZLoggerUnityDebugLoggerProvider is not thread safe #170 --- .../ZLoggerUnityDebugLoggerProvider.cs | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/ZLogger.Unity/Assets/ZLogger.Unity/Runtime/ZLoggerUnityDebugLoggerProvider.cs b/src/ZLogger.Unity/Assets/ZLogger.Unity/Runtime/ZLoggerUnityDebugLoggerProvider.cs index f8ae3a87..d2102c71 100644 --- a/src/ZLogger.Unity/Assets/ZLogger.Unity/Runtime/ZLoggerUnityDebugLoggerProvider.cs +++ b/src/ZLogger.Unity/Assets/ZLogger.Unity/Runtime/ZLoggerUnityDebugLoggerProvider.cs @@ -75,7 +75,7 @@ public void Post(IZLoggerEntry log) var msg = FormatToString(log, formatter); var unityLogType = log.LogInfo.AsUnityLogType(); - if (UnityEngine.Application.GetStackTraceLogType(unityLogType) != StackTraceLogType.None && options.PrettyStacktrace) + if (LogTypeMapper.GetStackTraceLogType(unityLogType) != StackTraceLogType.None && options.PrettyStacktrace) { var stacktrace = new StackTrace(5, true); msg = $"{msg}{Environment.NewLine}{DiagnosticsHelper.CleanupStackTrace(stacktrace)}{Environment.NewLine}---"; @@ -176,4 +176,30 @@ public void SetScopeProvider(IExternalScopeProvider scopeProvider) this.scopeProvider = scopeProvider; } } + + static class LogTypeMapper + { + static StackTraceLogType[]? stackTraceLogTypes = default!; + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + static void Init() + { + var logTypes = new[] { LogType.Error, LogType.Assert, LogType.Warning, LogType.Log, LogType.Exception }; + stackTraceLogTypes = new StackTraceLogType[logTypes.Length]; + for (int i = 0; i < logTypes.Length; i++) + { + stackTraceLogTypes[i] = UnityEngine.Application.GetStackTraceLogType(logTypes[i]); + } + } + + public static StackTraceLogType GetStackTraceLogType(LogType logType) + { + var i = (int)logType; + if (stackTraceLogTypes != null && i >= 0 && i < stackTraceLogTypes.Length) + { + return stackTraceLogTypes[i]; + } + return StackTraceLogType.None; + } + } } \ No newline at end of file