From f57b19ecc8a6dd7350d2018a932f2227be13b662 Mon Sep 17 00:00:00 2001 From: Natalie Bunduwongse Date: Tue, 13 Aug 2024 14:23:16 +1200 Subject: [PATCH] feat: add logging level --- .../Assets/Scripts/SelectAuthMethodScript.cs | 5 ++ sample/ProjectSettings/ProjectSettings.asset | 5 +- .../Core/BrowserCommunicationsManager.cs | 54 ++++++++++---- .../Runtime/Scripts/Private/Core/Logging.meta | 8 ++ .../Immutable.Passport.Core.Logging.asmdef | 14 ++++ ...mmutable.Passport.Core.Logging.asmdef.meta | 7 ++ .../Scripts/Private/Core/Logging/LogLevel.cs | 28 +++++++ .../Private/Core/Logging/LogLevel.cs.meta | 11 +++ .../Private/Core/Logging/PassportLogger.cs | 58 +++++++++++++++ .../Core/Logging/PassportLogger.cs.meta | 11 +++ .../Scripts/Private/Helpers/JsonHelpers.cs | 3 +- .../Scripts/Private/Helpers/UriHelpers.cs | 4 +- .../Immutable.Passport.Runtime.Private.asmdef | 3 +- .../Runtime/Scripts/Private/PassportImpl.cs | 74 ++++++++++++------- .../Public/Immutable.Passport.Runtime.asmdef | 6 +- .../Runtime/Scripts/Public/Passport.cs | 54 +++++++++++++- .../Gree/Assets/Plugins/GreeBrowserClient.cs | 7 +- .../Gree/Assets/Plugins/WebViewObject.cs | 59 ++++++++------- .../ThirdParty/Gree/unity-webview.asmdef | 3 +- .../Communication/TCPCommunicationLayer.cs | 3 - .../Runtime/Core/WebBrowserClient.cs | 14 +++- .../Logging/DefaultUnityWebBrowserLogger.cs | 23 +----- .../VoltstroStudios.UnityWebBrowser.asmdef | 3 +- 23 files changed, 347 insertions(+), 110 deletions(-) create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging.meta create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef.meta create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs.meta create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs create mode 100644 src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs.meta diff --git a/sample/Assets/Scripts/SelectAuthMethodScript.cs b/sample/Assets/Scripts/SelectAuthMethodScript.cs index 3e0bb829..e422602b 100644 --- a/sample/Assets/Scripts/SelectAuthMethodScript.cs +++ b/sample/Assets/Scripts/SelectAuthMethodScript.cs @@ -3,6 +3,7 @@ using UnityEngine.UI; using UnityEngine.SceneManagement; using Immutable.Passport; +using Immutable.Passport.Core.Logging; public class SelectAuthMethodScript : MonoBehaviour { @@ -68,6 +69,9 @@ private async void InitialisePassport(string redirectUri = null, string logoutRe try { + // Set the log level for the SDK + Passport.LogLevel = LogLevel.Info; + // Initialise Passport string clientId = "ZJL7JvetcDFBNDlgRs5oJoxuAUUl6uQj"; string environment = Immutable.Passport.Model.Environment.SANDBOX; @@ -79,6 +83,7 @@ private async void InitialisePassport(string redirectUri = null, string logoutRe } catch (Exception ex) { + Debug.LogException(ex, this); ShowOutput($"Initialise Passport error: {ex.Message}"); } } diff --git a/sample/ProjectSettings/ProjectSettings.asset b/sample/ProjectSettings/ProjectSettings.asset index 69b6286d..5b8b3f3a 100644 --- a/sample/ProjectSettings/ProjectSettings.asset +++ b/sample/ProjectSettings/ProjectSettings.asset @@ -769,7 +769,8 @@ PlayerSettings: webGLDecompressionFallback: 0 webGLPowerPreference: 2 scriptingDefineSymbols: - Standalone: + Android: VUPLEX_STANDALONE + Standalone: VUPLEX_STANDALONE additionalCompilerArguments: Standalone: - -nullable+ @@ -797,7 +798,7 @@ PlayerSettings: allowUnsafeCode: 0 useDeterministicCompilation: 1 enableRoslynAnalyzers: 1 - selectedPlatform: 0 + selectedPlatform: 2 additionalIl2CppArgs: scriptingRuntimeVersion: 1 gcIncremental: 1 diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs index 104ce615..7dce11c2 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs @@ -1,4 +1,3 @@ -using System.Net; using System; using Cysharp.Threading.Tasks; using System.Collections.Generic; @@ -7,6 +6,8 @@ using UnityEngine; using UnityEngine.Scripting; using Immutable.Passport.Helpers; +using Immutable.Passport.Core.Logging; +using Immutable.Passport.Event; namespace Immutable.Passport.Core { @@ -95,13 +96,23 @@ private void CallFunction(string requestId, string fxName, string data = null) // Call the function on the JS side string js = $"callFunction(\"{requestJson}\")"; - Debug.Log($"{TAG} Call {fxName} (request ID: {requestId}, js: {js})"); + + if (fxName != PassportAnalytics.TRACK) + { + string dataString = data != null ? $": {data}" : ""; + PassportLogger.Info($"{TAG} Call {fxName} (request ID: {requestId}){dataString}"); + } + else + { + PassportLogger.Debug($"{TAG} Call {fxName} (request ID: {requestId}): {js}"); + } + webBrowserClient.ExecuteJs(js); } public void LaunchAuthURL(string url, string redirectUri) { - Debug.Log($"{TAG} LaunchAuthURL : {url}"); + PassportLogger.Info($"{TAG} LaunchAuthURL : {url}"); webBrowserClient.LaunchAuthURL(url, redirectUri); } @@ -123,13 +134,12 @@ public void ClearStorage() private void InvokeOnUnityPostMessage(string message) { - Debug.Log($"{TAG} InvokeOnUnityPostMessage: {message}"); HandleResponse(message); } private void InvokeOnAuthPostMessage(string message) { - Debug.Log($"{TAG} InvokeOnAuthPostMessage: {message}"); + PassportLogger.Info($"{TAG} Auth message received: {message}"); if (OnAuthPostMessage != null) { OnAuthPostMessage.Invoke(message); @@ -138,7 +148,7 @@ private void InvokeOnAuthPostMessage(string message) private void InvokeOnPostMessageError(string id, string message) { - Debug.Log($"{TAG} InvokeOnPostMessageError id: {id} message: {message}"); + PassportLogger.Info($"{TAG} Error message received ({id}): {message}"); if (OnPostMessageError != null) { OnPostMessageError.Invoke(id, message); @@ -147,19 +157,32 @@ private void InvokeOnPostMessageError(string id, string message) private void HandleResponse(string message) { - Debug.Log($"{TAG} HandleResponse message: " + message); + PassportLogger.Debug($"{TAG} Handle response message: " + message); BrowserResponse response = message.OptDeserializeObject(); - // Check if the reponse returned is valid and the task to return the reponse exists - if (response == null || String.IsNullOrEmpty(response.responseFor) || String.IsNullOrEmpty(response.requestId)) + // Validate the deserialised response object + if (response == null || string.IsNullOrEmpty(response.responseFor) || string.IsNullOrEmpty(response.requestId)) + { + string responseError = "Response from browser is incorrect. Check game bridge file."; + PassportLogger.Error(responseError); + throw new PassportException(responseError); + } + + string logMessage = $"{TAG} Response for: {response.responseFor} (request ID: {response.requestId}) : {message}"; + if (response.responseFor != PassportAnalytics.TRACK) + { + // Log info messages for valid responses not related to tracking + PassportLogger.Info(logMessage); + } + else { - throw new PassportException($"Response from browser is incorrect. Check HTML/JS files."); + PassportLogger.Debug(logMessage); } - // Special case to detect if index.js is loaded + // Handle special case where the response indicates that the browser is ready if (response.responseFor == INIT && response.requestId == INIT_REQUEST_ID) { - Debug.Log($"{TAG} Browser is ready"); + PassportLogger.Info($"{TAG} Browser is ready"); if (OnReady != null) { OnReady.Invoke(); @@ -167,6 +190,7 @@ private void HandleResponse(string message) return; } + // Handle the response if a matching task exists for the request ID string requestId = response.requestId; if (requestTaskMap.ContainsKey(requestId)) { @@ -174,7 +198,9 @@ private void HandleResponse(string message) } else { - throw new PassportException($"No TaskCompletionSource for request id {requestId} found."); + string errorMsg = $"No TaskCompletionSource for request id {requestId} found."; + PassportLogger.Error(errorMsg); + throw new PassportException(errorMsg); } } @@ -199,7 +225,7 @@ private PassportException ParseError(BrowserResponse response) } catch (Exception ex) { - Debug.LogError($"{TAG} Parse passport type error: {ex.Message}"); + PassportLogger.Error($"{TAG} Parse passport type error: {ex.Message}"); } return new PassportException(response.error ?? "Failed to parse error"); } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging.meta b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging.meta new file mode 100644 index 00000000..184580a9 --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 18ccfd2d3f2674e4aab0f0f8f924f667 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef new file mode 100644 index 00000000..76ebfab6 --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef @@ -0,0 +1,14 @@ +{ + "name": "Immutable.Passport.Core.Logging", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef.meta b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef.meta new file mode 100644 index 00000000..b8ee01e4 --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a0996310e1aa34b7fbf14df5d255461d +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs new file mode 100644 index 00000000..680a2c53 --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs @@ -0,0 +1,28 @@ +namespace Immutable.Passport.Core.Logging +{ + /// + /// Defines the logging levels used within the SDK to categorise the severity of log messages. + /// + public enum LogLevel + { + /// + /// Logs detailed information for debugging the SDK + /// + Debug, + + /// + /// Logs general information about SDK operations + /// + Info, + + /// + /// Logs warnings about potential issues or unexpected behaviour + /// + Warn, + + /// + /// Logs errors indicating failures in SDK operations + /// + Error + } +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs.meta b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs.meta new file mode 100644 index 00000000..c75673a5 --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81394a9b944f94a5fa09448bc7178988 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs new file mode 100644 index 00000000..905a8dce --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs @@ -0,0 +1,58 @@ +using UnityEngine; + +namespace Immutable.Passport.Core.Logging +{ + public static class PassportLogger + { + private const string TAG = "[Immutable]"; + + public static LogLevel CurrentLogLevel { get; set; } = LogLevel.Info; + + public static void Log(LogLevel level, string message) + { + if (level < CurrentLogLevel) + { + return; // Don't log messages below the current log level + } + + switch (level) + { + case LogLevel.Debug: + UnityEngine.Debug.Log($"{TAG} {message}"); + break; + case LogLevel.Info: + UnityEngine.Debug.Log($"{TAG} {message}"); + break; + case LogLevel.Warn: + UnityEngine.Debug.LogWarning($"{TAG} {message}"); + break; + case LogLevel.Error: + UnityEngine.Debug.LogError($"{TAG} {message}"); + break; + default: + break; + } + } + + public static void Debug(string message) + { + Log(LogLevel.Debug, message); + } + + public static void Info(string message) + { + Log(LogLevel.Info, message); + } + + public static void Warn(string message) + { + Log(LogLevel.Warn, message); + } + + public static void Error(string message) + { + Log(LogLevel.Error, message); + } + } + +} diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs.meta b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs.meta new file mode 100644 index 00000000..ca7ae428 --- /dev/null +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f03a90f57656e477990d0eeb937cb339 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs index f9b6f316..2080dae7 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using UnityEngine; +using Immutable.Passport.Core.Logging; namespace Immutable.Passport.Helpers { @@ -19,7 +20,7 @@ public static T OptDeserializeObject(this string json) where T : class } catch (Exception e) { - Debug.Log($"Failed to deserialise {json}: {e.Message}"); + PassportLogger.Debug($"Failed to deserialise {json}: {e.Message}"); return null; } } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs index 7041714b..895002e3 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs @@ -1,5 +1,5 @@ using System; -using UnityEngine; +using Immutable.Passport.Core.Logging; namespace Immutable.Passport.Helpers { @@ -25,7 +25,7 @@ public static string GetQueryParameter(this Uri uri, string key) } catch (Exception e) { - Debug.Log($"Failed to get query parameter {key}: {e.Message}"); + PassportLogger.Debug($"Failed to get query parameter {key}: {e.Message}"); } return null; } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef b/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef index 753e79a1..afa21bb6 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef +++ b/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef @@ -5,7 +5,8 @@ "VoltstroStudios.UnityWebBrowser", "UniTask", "Immutable.Browser.Core", - "unity-webview" + "unity-webview", + "Immutable.Passport.Core.Logging" ], "includePlatforms": [ "Android", diff --git a/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs b/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs index 440cb483..0b958981 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs @@ -7,7 +7,7 @@ using Immutable.Passport.Core; using Immutable.Passport.Helpers; using Cysharp.Threading.Tasks; -using UnityEngine.Analytics; +using Immutable.Passport.Core.Logging; #if UNITY_ANDROID using UnityEngine.Android; #endif @@ -143,6 +143,12 @@ await ConfirmCode( } } + /// + /// Attempts to re-login using saved credentials. + /// + /// + /// Returns true if re-login is successful, otherwise false. + /// private async UniTask Relogin() { try @@ -153,13 +159,17 @@ private async UniTask Relogin() Track(PassportAnalytics.EventName.COMPLETE_RELOGIN, success: true); SendAuthEvent(PassportAuthEvent.ReloginSuccess); isLoggedIn = true; + return true; } catch (Exception ex) { - Debug.Log($"{TAG} Failed to login to Passport using saved credentials: {ex.Message}"); + // Log a warning if re-login fails. + PassportLogger.Warn($"{TAG} Failed to login using saved credentials. " + + $"Please check if user has saved credentials first by calling HasCredentialsSaved() : {ex.Message}"); isLoggedIn = false; } + Track(PassportAnalytics.EventName.COMPLETE_RELOGIN, success: false); SendAuthEvent(PassportAuthEvent.ReloginFailed); return false; @@ -211,11 +221,16 @@ await ConfirmCode( } } + /// + /// Attempts to reconnect using saved credentials. + /// + /// True if reconnect is successful, otherwise false. private async UniTask Reconnect() { try { SendAuthEvent(PassportAuthEvent.Reconnecting); + string callResponse = await communicationsManager.Call(PassportFunction.RECONNECT); Track(PassportAnalytics.EventName.COMPLETE_RECONNECT, success: true); @@ -225,9 +240,13 @@ private async UniTask Reconnect() } catch (Exception ex) { - Debug.Log($"{TAG} Failed to connect to Passport using saved credentials: {ex.Message}"); + // Log a warning if reconnect fails. + PassportLogger.Warn($"{TAG} Failed to connect using saved credentials. " + + $"Please check if user has saved credentials first by calling HasCredentialsSaved() : {ex.Message}"); + isLoggedIn = false; } + Track(PassportAnalytics.EventName.COMPLETE_RECONNECT, success: false); SendAuthEvent(PassportAuthEvent.ReconnectFailed); return false; @@ -294,7 +313,7 @@ public async void OnDeepLinkActivated(string url) { try { - Debug.Log($"{TAG} OnDeepLinkActivated URL: {url}"); + PassportLogger.Info($"{TAG} Received deeplink URL: {url}"); Uri uri = new Uri(url); string domain = $"{uri.Scheme}://{uri.Host}{uri.AbsolutePath}"; @@ -312,9 +331,9 @@ public async void OnDeepLinkActivated(string url) await CompleteLoginPKCEFlow(url); } } - catch (Exception e) + catch (Exception ex) { - Debug.LogError($"{TAG} OnDeepLinkActivated error {url}: {e.Message}"); + PassportLogger.Error($"{TAG} Deeplink error {url}: {ex.Message}"); } } @@ -334,7 +353,7 @@ public UniTask LoginPKCE() catch (Exception ex) { string errorMessage = $"Failed to log in using PKCE flow: {ex.Message}"; - Debug.Log($"{TAG} {errorMessage}"); + PassportLogger.Error($"{TAG} {errorMessage}"); Track(PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE, success: false); SendAuthEvent(PassportAuthEvent.LoginPKCEFailed); @@ -357,7 +376,7 @@ public UniTask ConnectImxPKCE() catch (Exception ex) { string errorMessage = $"Failed to connect using PKCE flow: {ex.Message}"; - Debug.Log($"{TAG} {errorMessage}"); + PassportLogger.Error($"{TAG} {errorMessage}"); Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, success: false); SendAuthEvent(PassportAuthEvent.ConnectImxPKCEFailed); @@ -387,17 +406,17 @@ private async UniTask LaunchAuthUrl() } else { - Debug.Log($"{TAG} Failed to get PKCE Auth URL"); + PassportLogger.Error($"{TAG} Failed to get PKCE Auth URL"); } } catch (Exception e) { - Debug.Log($"{TAG} Get PKCE Auth URL error: {e.Message}"); + PassportLogger.Error($"{TAG} Get PKCE Auth URL error: {e.Message}"); } await UniTask.SwitchToMainThread(); TrySetPKCEException(new PassportException( - "Something went wrong, please call ConnectImxPKCE() again", + "Something went wrong, please call LoginPKCE() or ConnectImxPKCE() again", PassportErrorType.AUTHENTICATION_ERROR )); } @@ -491,16 +510,15 @@ public async UniTask CompleteLoginPKCEFlow(string uriString) #if UNITY_ANDROID public void OnLoginPKCEDismissed(bool completing) { - Debug.Log($"{TAG} On Login PKCE Dismissed"); if (!completing && !isLoggedIn) { // User hasn't entered all required details (e.g. email address) into Passport yet - Debug.Log($"{TAG} Login PKCE dismissed before completing the flow"); + PassportLogger.Info($"{TAG} Login PKCE dismissed before completing the flow"); TrySetPKCECanceled(); } else { - Debug.Log($"{TAG} Login PKCE dismissed by user or SDK"); + PassportLogger.Info($"{TAG} Login PKCE dismissed by user or SDK"); } loginPKCEUrl = null; } @@ -544,7 +562,7 @@ public async UniTask Logout(bool hardLogout = true) catch (Exception ex) { string errorMessage = $"Failed to log out: {ex.Message}"; - Debug.Log($"{TAG} {errorMessage}"); + PassportLogger.Error($"{TAG} {errorMessage}"); Track(PassportAnalytics.EventName.COMPLETE_LOGOUT, success: false); SendAuthEvent(PassportAuthEvent.LogoutFailed); @@ -566,7 +584,7 @@ public UniTask LogoutPKCE(bool hardLogout = true) catch (Exception ex) { string errorMessage = $"Failed to log out: {ex.Message}"; - Debug.Log($"{TAG} {errorMessage}"); + PassportLogger.Error($"{TAG} {errorMessage}"); Track(PassportAnalytics.EventName.COMPLETE_LOGOUT_PKCE, success: false); SendAuthEvent(PassportAuthEvent.LogoutPKCEFailed); @@ -617,7 +635,7 @@ public async UniTask HasCredentialsSaved() catch (Exception ex) { string errorMessage = $"Failed to check if there are credentials saved: {ex.Message}"; - Debug.Log($"{TAG} {errorMessage}"); + PassportLogger.Debug($"{TAG} {errorMessage}"); SendAuthEvent(PassportAuthEvent.CheckForSavedCredentialsFailed); return false; } @@ -764,7 +782,7 @@ private async void OnPostMessageError(string id, string message) } else { - Debug.LogError($"{TAG} id: {id} err: {message}"); + PassportLogger.Error($"{TAG} id: {id} err: {message}"); } } @@ -774,14 +792,14 @@ private async UniTask CallFromAuthCallbackError(string id, string message) if (message == "") { - Debug.Log($"{TAG} Get PKCE Auth URL user cancelled"); + PassportLogger.Warn($"{TAG} Get PKCE Auth URL user cancelled"); TrySetPKCECanceled(); } else { - Debug.Log($"{TAG} Get PKCE Auth URL error: {message}"); + PassportLogger.Error($"{TAG} Get PKCE Auth URL error: {message}"); TrySetPKCEException(new PassportException( - "Something went wrong, please call ConnectPKCEImx() again", + "Something went wrong, please call LoginPKCE() or ConnectPKCEImx() again", PassportErrorType.AUTHENTICATION_ERROR )); } @@ -791,46 +809,46 @@ private async UniTask CallFromAuthCallbackError(string id, string message) private void TrySetPKCEResult(bool result) { - Debug.Log($"{TAG} Trying to set PKCE result to {result}..."); + PassportLogger.Debug($"{TAG} Trying to set PKCE result to {result}..."); if (pkceCompletionSource != null) { pkceCompletionSource.TrySetResult(result); } else { - Debug.LogError($"{TAG} PKCE completed with {result} but unable to bind result"); + PassportLogger.Error($"{TAG} PKCE completed with {result} but unable to bind result"); } } private void TrySetPKCEException(Exception exception) { - Debug.Log($"{TAG} Trying to set PKCE exception..."); + PassportLogger.Debug($"{TAG} Trying to set PKCE exception..."); if (pkceCompletionSource != null) { pkceCompletionSource.TrySetException(exception); } else { - Debug.LogError($"{TAG} {exception.Message}"); + PassportLogger.Error($"{TAG} {exception.Message}"); } } private void TrySetPKCECanceled() { - Debug.Log($"{TAG} Trying to set PKCE canceled..."); + PassportLogger.Debug($"{TAG} Trying to set PKCE canceled..."); if (pkceCompletionSource != null) { pkceCompletionSource.TrySetCanceled(); } else { - Debug.LogWarning($"{TAG} PKCE canceled"); + PassportLogger.Warn($"{TAG} PKCE canceled"); } } private void SendAuthEvent(PassportAuthEvent authEvent) { - Debug.Log($"{TAG} Send auth event: {authEvent}"); + PassportLogger.Debug($"{TAG} Send auth event: {authEvent}"); if (OnAuthEvent != null) { OnAuthEvent.Invoke(authEvent); diff --git a/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef b/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef index d0cb58cb..882b7caa 100644 --- a/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef +++ b/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef @@ -6,7 +6,8 @@ "UniTask", "Immutable.Browser.Core", "unity-webview", - "Immutable.Passport.Runtime.Private" + "Immutable.Passport.Runtime.Private", + "Immutable.Passport.Core.Logging" ], "includePlatforms": [ "Android", @@ -19,7 +20,8 @@ "allowUnsafeCode": false, "overrideReferences": true, "precompiledReferences": [ - "Newtonsoft.Json.dll" + "Newtonsoft.Json.dll", + "VoltstroStudios.UnityWebBrowser.Shared.dll" ], "autoReferenced": true, "defineConstraints": [], diff --git a/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs b/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs index 9d825ac7..6cda5e6b 100644 --- a/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs +++ b/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs @@ -3,6 +3,7 @@ #if UNITY_STANDALONE_WIN || (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN) #if !IMMUTABLE_CUSTOM_BROWSER using VoltstroStudios.UnityWebBrowser.Core; +using VoltstroStudios.UnityWebBrowser.Shared; #endif #elif (UNITY_ANDROID && !UNITY_EDITOR_WIN) || (UNITY_IPHONE && !UNITY_EDITOR_WIN) || UNITY_STANDALONE_OSX using Immutable.Browser.Gree; @@ -11,6 +12,7 @@ using Immutable.Browser.Core; using Immutable.Passport.Model; using Immutable.Passport.Core; +using Immutable.Passport.Core.Logging; using Cysharp.Threading.Tasks; using UnityEngine; #if UNITY_EDITOR @@ -39,6 +41,31 @@ public class Passport /// public event OnAuthEventDelegate OnAuthEvent; + /// + /// The log level for the SDK. + /// + /// + /// The log level determines which messages are recorded based on their severity. The default value is . + /// + /// See for valid log levels and their meanings. + /// + /// + public static LogLevel LogLevel + { + get => _logLevel; + set + { + _logLevel = value; + PassportLogger.CurrentLogLevel = _logLevel; + +#if !IMMUTABLE_CUSTOM_BROWSER && (UNITY_STANDALONE_WIN || (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN)) + SetDefaultWindowsBrowserLogLevel(); +#endif + } + } + + private static LogLevel _logLevel = LogLevel.Info; + private Passport() { // Handle clean-up tasks when the application is quitting @@ -84,7 +111,7 @@ public static UniTask Init( { if (Instance == null) { - Debug.Log($"{TAG} Initialising Passport..."); + PassportLogger.Info($"{TAG} Initialising Passport..."); Instance = new Passport(); // Start initialisation process @@ -96,7 +123,7 @@ public static UniTask Init( .ContinueWith(async () => { // Wait for the ready signal - Debug.Log($"{TAG} Waiting for ready signal..."); + PassportLogger.Info($"{TAG} Waiting for ready signal..."); await UniTask.WaitUntil(() => readySignalReceived == true); }) .ContinueWith(async () => @@ -109,7 +136,7 @@ public static UniTask Init( } else { - Debug.Log($"{TAG} Failed to initialise Passport"); + PassportLogger.Error($"{TAG} Failed to initialise Passport"); throw new PassportException("Failed to initiliase Passport", PassportErrorType.INITALISATION_ERROR); } }); @@ -465,6 +492,25 @@ public void ClearStorage() } #endif +#if !IMMUTABLE_CUSTOM_BROWSER && (UNITY_STANDALONE_WIN || (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN)) + /// + /// Updates the log severity for the default Windows browser based on the current SDK log level. + /// + private static void SetDefaultWindowsBrowserLogLevel() + { + if (Instance?.webBrowserClient is WebBrowserClient browserClient) + { + browserClient.logSeverity = _logLevel switch + { + LogLevel.Debug => LogSeverity.Debug, + LogLevel.Warn => LogSeverity.Warn, + LogLevel.Error => LogSeverity.Error, + _ => LogSeverity.Info + }; + } + } +#endif + private PassportImpl GetPassportImpl() { if (passportImpl != null) @@ -497,7 +543,7 @@ private void OnPassportAuthEvent(PassportAuthEvent authEvent) /// private void OnQuit() { - Debug.Log($"{TAG} Quitting the Player"); + PassportLogger.Info($"{TAG} Cleaning up Passport..."); #if UNITY_EDITOR EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; diff --git a/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/GreeBrowserClient.cs b/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/GreeBrowserClient.cs index 9fbea807..661c0460 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/GreeBrowserClient.cs +++ b/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/GreeBrowserClient.cs @@ -1,8 +1,7 @@ #if (UNITY_ANDROID && !UNITY_EDITOR_WIN) || (UNITY_IPHONE && !UNITY_EDITOR_WIN) || UNITY_STANDALONE_OSX using Immutable.Browser.Core; -using UnityEngine; -using System.IO; +using Immutable.Passport.Core.Logging; namespace Immutable.Browser.Gree { @@ -18,7 +17,7 @@ public class GreeBrowserClient : IWebBrowserClient public GreeBrowserClient() { #if (UNITY_ANDROID && UNITY_EDITOR_OSX) || (UNITY_IPHONE && UNITY_EDITOR_OSX) - Debug.LogWarning("Native Android and iOS WebViews cannot run in the Editor, so the macOS WebView is currently used to save your development time." + + PassportLogger.Warn("Native Android and iOS WebViews cannot run in the Editor, so the macOS WebView is currently used to save your development time." + " Testing your game on an actual device or emulator is recommended to ensure proper functionality."); #endif webViewObject = new WebViewObject(); @@ -59,7 +58,7 @@ internal void InvokeOnUnityPostMessage(string message) internal void InvokeOnLogMessage(string message) { - Debug.Log($"{TAG} InvokeOnLogMessage {message}"); + PassportLogger.Debug($"{TAG} Console log: {message}"); } public void ExecuteJs(string js) diff --git a/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/WebViewObject.cs b/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/WebViewObject.cs index 5344633c..453f236b 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/WebViewObject.cs +++ b/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/WebViewObject.cs @@ -19,18 +19,14 @@ * 3. This notice may not be removed or altered from any source distribution. */ +using Immutable.Passport.Core.Logging; using UnityEngine; using System; -using System.Collections; -using System.Collections.Generic; using System.Runtime.InteropServices; #if UNITY_2018_4_OR_NEWER using UnityEngine.Networking; #endif #if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX -using System.IO; -using System.Text.RegularExpressions; -using UnityEngine.Rendering; #endif #if UNITY_ANDROID using UnityEngine.Android; @@ -45,7 +41,7 @@ namespace Immutable.Browser.Gree { #if UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX - public class Singleton + public class Singleton { private static Singleton _instance; public Callback onJS; @@ -143,42 +139,53 @@ private static extern void _CWebViewPlugin_EvaluateJS( #if UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX private delegate void DelegateMessage(string key, string message); - - [MonoPInvokeCallback(typeof(DelegateMessage))] - private static void delegateMessageReceived(string key, string message) { - if (key == "CallOnLog") { - if (Singleton.Instance.onLog != null) { + + [MonoPInvokeCallback(typeof(DelegateMessage))] + private static void delegateMessageReceived(string key, string message) + { + if (key == "CallOnLog") + { + if (Singleton.Instance.onLog != null) + { Singleton.Instance.onLog(message); } } - if (key == "CallFromJS") { - if (Singleton.Instance.onJS != null) { - Debug.Log($"{TAG} ==== onJS callback running message: " + message); + if (key == "CallFromJS") + { + if (Singleton.Instance.onJS != null) + { + PassportLogger.Debug($"{TAG} onJS: " + message); Singleton.Instance.onJS(message); } return; } - if (key == "CallOnError" || key == "CallFromAuthCallbackError") { - if (Singleton.Instance.onError != null) { - Debug.Log($"{TAG} ==== onError callback running message: " + message); + if (key == "CallOnError" || key == "CallFromAuthCallbackError") + { + if (Singleton.Instance.onError != null) + { + PassportLogger.Debug($"{TAG} onError: " + message); Singleton.Instance.onError(key, message); } return; } - if (key == "CallOnHttpError") { - if (Singleton.Instance.onHttpError != null) { - Debug.Log($"{TAG} ==== onHttpError callback running message: " + message); + if (key == "CallOnHttpError") + { + if (Singleton.Instance.onHttpError != null) + { + PassportLogger.Debug($"{TAG} onHttpError: " + message); Singleton.Instance.onHttpError(key, message); } return; } - if (key == "CallFromAuthCallback") { - if (Singleton.Instance.onAuth != null) { - Debug.Log($"{TAG} ==== CallFromAuthCallback callback running message: " + message); + if (key == "CallFromAuthCallback") + { + if (Singleton.Instance.onAuth != null) + { + PassportLogger.Debug($"{TAG} CallFromAuthCallback: " + message); Singleton.Instance.onAuth(message); } return; @@ -229,7 +236,7 @@ public void Init( Application.ExternalCall("unityWebView.init"); #elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX //TODO: UNSUPPORTED - Debug.LogError("Webview is not supported on this platform."); + PassportLogger.Error("Webview is not supported on this platform."); #elif UNITY_IPHONE || UNITY_STANDALONE_OSX || (UNITY_ANDROID && UNITY_EDITOR_OSX) webView = _CWebViewPlugin_Init(ua); Singleton.Instance.onJS = ((message) => CallFromJS(message)); @@ -243,7 +250,7 @@ public void Init( webView.Call("Init", ua); webView.Call("setCallback", new AndroidCallback((message) => handleMessage(message))); #else - Debug.LogError("Webview is not supported on this platform."); + Logger.Error("Webview is not supported on this platform."); #endif } @@ -302,7 +309,7 @@ public void LaunchAuthURL(string url, string redirectUri) return; _CWebViewPlugin_LaunchAuthURL(webView, url); #else - Application.OpenURL(url); + UnityEngine.Application.OpenURL(url); #endif } diff --git a/src/Packages/Passport/Runtime/ThirdParty/Gree/unity-webview.asmdef b/src/Packages/Passport/Runtime/ThirdParty/Gree/unity-webview.asmdef index 66923203..cc46948b 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/Gree/unity-webview.asmdef +++ b/src/Packages/Passport/Runtime/ThirdParty/Gree/unity-webview.asmdef @@ -2,7 +2,8 @@ "name": "unity-webview", "rootNamespace": "", "references": [ - "GUID:95d173a3e67b39d40803000ed05b79f4" + "GUID:95d173a3e67b39d40803000ed05b79f4", + "GUID:a0996310e1aa34b7fbf14df5d255461d" ], "includePlatforms": [ "Android", diff --git a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Communication/TCPCommunicationLayer.cs b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Communication/TCPCommunicationLayer.cs index 207d1b19..1f96cfb7 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Communication/TCPCommunicationLayer.cs +++ b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Communication/TCPCommunicationLayer.cs @@ -65,7 +65,6 @@ public override void GetIpcSettings(out object outLocation, out object inLocatio } private bool CheckAvailableServerPort(int port) { - Debug.Log($"Checking Port {port}"); bool isAvailable = true; IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); @@ -78,8 +77,6 @@ private bool CheckAvailableServerPort(int port) { } } - Debug.Log($"Port {port} available = {isAvailable}"); - return isAvailable; } } diff --git a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Core/WebBrowserClient.cs b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Core/WebBrowserClient.cs index 9efb2eaf..81266e3b 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Core/WebBrowserClient.cs +++ b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Core/WebBrowserClient.cs @@ -13,6 +13,7 @@ using System.Threading.Tasks; using Cysharp.Threading.Tasks; using Immutable.Browser.Core; +using Immutable.Passport.Core.Logging; using Unity.Collections; using Unity.Profiling; using UnityEngine; @@ -253,7 +254,7 @@ public IWebBrowserLogger Logger public WebBrowserClient() { #if (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN) - UnityEngine.Debug.LogWarning("Native Android and iOS WebViews cannot run in the Editor, so the Windows WebView is currently used to save your development time." + + logger.Warn("Native Android and iOS WebViews cannot run in the Editor, so the Windows WebView is currently used to save your development time." + " Testing your game on an actual device or emulator is recommended to ensure proper functionality."); #endif } @@ -264,8 +265,17 @@ public WebBrowserClient() /// public async UniTask Init(int engineStartupTimeout = 30000) { + // Set log level + logSeverity = PassportLogger.CurrentLogLevel switch + { + LogLevel.Debug => LogSeverity.Debug, + LogLevel.Warn => LogSeverity.Warn, + LogLevel.Error => LogSeverity.Error, + _ => LogSeverity.Info + }; + this.engineStartupTimeout = engineStartupTimeout; - UnityEngine.Debug.Log($"{TAG} Engine startup timeout: {engineStartupTimeout}"); + logger.Debug($"{TAG} Engine startup timeout: {engineStartupTimeout}"); // Get the path to the Windows UWB process EngineConfiguration engineConfiguration = new EngineConfiguration(); diff --git a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Logging/DefaultUnityWebBrowserLogger.cs b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Logging/DefaultUnityWebBrowserLogger.cs index 6c58d311..a3240867 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Logging/DefaultUnityWebBrowserLogger.cs +++ b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/Logging/DefaultUnityWebBrowserLogger.cs @@ -1,41 +1,26 @@ #if !IMMUTABLE_CUSTOM_BROWSER && (UNITY_STANDALONE_WIN || (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN)) -// UnityWebBrowser (UWB) -// Copyright (c) 2021-2022 Voltstro-Studios -// -// This project is under the MIT license. See the LICENSE.md file for more details. - -using UnityEngine; +using Immutable.Passport.Core.Logging; namespace VoltstroStudios.UnityWebBrowser.Logging { - /// - /// An using Unity's - /// public sealed class DefaultUnityWebBrowserLogger : IWebBrowserLogger { private const string LoggingTag = "[Web Browser]"; - private readonly ILogger logger; - - public DefaultUnityWebBrowserLogger() - { - logger = UnityEngine.Debug.unityLogger; - } - public void Debug(object message) { - logger.Log(LogType.Log, LoggingTag, message); + PassportLogger.Debug($"{LoggingTag} {message}"); } public void Warn(object message) { - logger.LogWarning(LoggingTag, message); + PassportLogger.Warn($"{LoggingTag} {message}"); } public void Error(object message) { - logger.LogError(LoggingTag, message); + PassportLogger.Error($"{LoggingTag} {message}"); } } } diff --git a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef index 62af4a14..0c0060d2 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef +++ b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef @@ -4,7 +4,8 @@ "references": [ "UniTask", "Unity.InputSystem", - "Immutable.Browser.Core" + "Immutable.Browser.Core", + "Immutable.Passport.Core.Logging" ], "includePlatforms": [ "Editor",