Skip to content

Commit

Permalink
cleanup of old logger calls
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohit Tejani authored and Mohit Tejani committed Mar 3, 2025
1 parent ca8d47a commit 164a41f
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 62 deletions.
39 changes: 17 additions & 22 deletions src/Api/PubnubApi/EndPoint/TokenManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class TokenManager : IDisposable
private readonly IJsonPluggableLibrary jsonLib;
private readonly IPubnubLog pubnubLog;
private readonly string pubnubInstanceId;
private readonly PubnubLogModule logger;
private static ConcurrentDictionary<string, string> dToken
{
get;
Expand All @@ -28,10 +29,11 @@ private static ConcurrentDictionary<string, string> dToken

public TokenManager(PNConfiguration config, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubLog log, string instanceId)
{
this.pubnubConfig = config;
this.pubnubLog = log;
this.jsonLib = jsonPluggableLibrary;
this.pubnubInstanceId = instanceId;
pubnubConfig = config;
pubnubLog = log;
jsonLib = jsonPluggableLibrary;
pubnubInstanceId = instanceId;
logger = config.Logger;
if (!dToken.ContainsKey(instanceId))
{
dToken.TryAdd(instanceId, null);
Expand Down Expand Up @@ -73,11 +75,11 @@ public PNTokenContent ParseToken(string token)
{
string refinedToken = token.Replace('_', '/').Replace('-', '+');
byte[] tokenByteArray = Convert.FromBase64String(refinedToken);
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] Token Bytes = {GetDisplayableBytes(tokenByteArray)}", PNLogVerbosity.BODY);
logger?.Debug($"TokenManager Token Bytes = {GetDisplayableBytes(tokenByteArray)}");
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(tokenByteArray))
{
CBORObject cborObj = CBORObject.DecodeFromBytes(tokenByteArray);
LoggingMethod.WriteToLog(pubnubLog,$"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}], RAW CBOR {cborObj.ToJSONString()}",(pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"RAW CBOR {cborObj.ToJSONString()}");

if (cborObj != null)
{
Expand Down Expand Up @@ -105,14 +107,7 @@ public PNTokenContent ParseToken(string token)
}
catch (Exception ex)
{
if (this.pubnubLog != null && this.pubnubConfig != null)
{
LoggingMethod.WriteToLog(pubnubLog, ex.ToString(), pubnubConfig.LogVerbosity);
}
else
{
System.Diagnostics.Debug.WriteLine(ex);
}
logger?.Error($"Error parsing token: {ex.Message} \n {ex.StackTrace}");
}
return result;
}
Expand All @@ -134,12 +129,12 @@ private void ParseCBOR(CBORObject cbor, string parent, ref PNTokenContent pnGran
}
else if (kvp.Key.Type.ToString().Equals("TextString", StringComparison.OrdinalIgnoreCase))
{
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] TextString Key {kvp.Key}-{kvp.Value}-{kvp.Value.Type}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"ParseCBOR TextString Key {kvp.Key}-{kvp.Value}-{kvp.Value.Type}");
ParseCBORValue(kvp.Key.ToString(), parent, kvp, ref pnGrantTokenDecoded);
}
else
{
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] Others Key {kvp.Key}-{kvp.Key.Type}-{kvp.Value}-{kvp.Value.Type}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"Others Key {kvp.Key}-{kvp.Key.Type}-{kvp.Value}-{kvp.Value.Type}");
}

}
Expand All @@ -149,7 +144,7 @@ private void ParseCBORValue(string key, string parent, KeyValuePair<CBORObject,
{
if (kvp.Value.Type.ToString().Equals("Map", StringComparison.OrdinalIgnoreCase))
{
LoggingMethod.WriteToLog(pubnubLog,$"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] Map Key {key}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"ParseCBORValue Map Key {key}");
var p = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", parent, string.IsNullOrEmpty(parent) ? "" : ":", key);
ParseCBOR(kvp.Value, p, ref pnGrantTokenDecoded);
}
Expand All @@ -160,24 +155,24 @@ private void ParseCBORValue(string key, string parent, KeyValuePair<CBORObject,
byte[] valBytes = kvp.Value.GetByteString();
string val = utf8.GetString(valBytes, 0, valBytes.Length);
#else
string val = System.Text.Encoding.ASCII.GetString(kvp.Value.GetByteString());
string val = Encoding.ASCII.GetString(kvp.Value.GetByteString());
#endif
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}], ByteString Value {key}-{val}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"ByteString Value {key}-{val}");
FillGrantToken(parent, key, kvp.Value, typeof(string), ref pnGrantTokenDecoded);
}
else if (kvp.Value.Type.ToString().Equals("Integer", StringComparison.OrdinalIgnoreCase))
{
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] Integer Value {key}-{kvp.Value}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($" Integer Value {key}-{kvp.Value}");
FillGrantToken(parent, key, kvp.Value, typeof(int), ref pnGrantTokenDecoded);
}
else if (kvp.Value.Type.ToString().Equals("TextString", StringComparison.OrdinalIgnoreCase))
{
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] TextString Value {key}-{kvp.Value}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"TextString Value {key}-{kvp.Value}");
FillGrantToken(parent, key, kvp.Value, typeof(string), ref pnGrantTokenDecoded);
}
else
{
LoggingMethod.WriteToLog(pubnubLog, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] Others Key Value {kvp.Key.Type}-{kvp.Value.Type}-{key}-{kvp.Value}", (pubnubConfig != null) ? pubnubConfig.LogVerbosity : PNLogVerbosity.NONE);
logger?.Debug($"Others Key Value {kvp.Key.Type}-{kvp.Value.Type}-{key}-{kvp.Value}");
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,8 @@ public void EmitEvent<T>(object e)
}
catch (Exception ex)
{
LoggingMethod.WriteToLog(this.log, $"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] Error: Listener call back execution encounters error: {ex.Message}\n{ex?.StackTrace}", configuration.LogVerbosity);
configuration.Logger?.Error(
$"Listener call back execution encounters error: {ex.Message}\n{ex?.StackTrace}");
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/Api/PubnubApi/EventEngine/Core/Engine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,18 @@ private async Task Transition(IEvent e)
/// Launch the invocations associated with transitioning between states
/// </summary>
private async Task ExecuteStateChange(State sourceState, State targetState, IEnumerable<IEffectInvocation> invocations) {
logger.Debug($"Exiting state {sourceState}");
logger?.Debug($"Exiting state {sourceState}");
foreach (var effectInvocation in sourceState.OnExit ?? emptyInvocationList) {
logger.Debug($"Dispatching effect: {effectInvocation}");
logger?.Debug($"Dispatching effect: {effectInvocation}");
await dispatcher.Dispatch(effectInvocation);
}
foreach (var effectInvocation in invocations ?? emptyInvocationList) {
logger.Debug($"Dispatching effect: {effectInvocation}");
logger?.Debug($"Dispatching effect: {effectInvocation}");
await dispatcher.Dispatch(effectInvocation);
}
logger.Debug($"Entering state {targetState}");
logger?.Debug($"Entering state {targetState}");
foreach (var effectInvocation in targetState.OnEntry ?? emptyInvocationList) {
logger.Debug($"Dispatching effect: {effectInvocation}");
logger?.Debug($"Dispatching effect: {effectInvocation}");
await dispatcher.Dispatch(effectInvocation);
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/Api/PubnubApi/NewtonsoftJsonDotNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public object DeserializeToObject(object rawObject, Type type)
{
try
{
logger.Debug("JsonNet Deserializing object data.");
logger?.Debug("JsonNet Deserializing object data.");
if (rawObject is JObject jObject)
{
return jObject.ToObject(type);
Expand All @@ -180,14 +180,14 @@ public object DeserializeToObject(object rawObject, Type type)
}
catch (Exception e)
{
logger.Error($"Deserialize To Object failed with exception {e.Message}, stack trace {e.StackTrace}");
logger?.Error($"Deserialize To Object failed with exception {e.Message}, stack trace {e.StackTrace}");
return rawObject;
}
}

public object DeserializeToObject(string jsonString)
{
logger.Debug("JsonNet Deserializing json string data.");
logger?.Debug("JsonNet Deserializing json string data.");
object result = JsonConvert.DeserializeObject<object>(jsonString,
new JsonSerializerSettings { DateParseHandling = DateParseHandling.None, MaxDepth = 64 });
if (result.GetType().ToString() == "Newtonsoft.Json.Linq.JArray")
Expand All @@ -208,7 +208,7 @@ public object DeserializeToObject(string jsonString)
result = objectContainer;
}
}
logger.Debug("JsonNet Deserialsed json string data successfully.");
logger?.Debug("JsonNet Deserialsed json string data successfully.");
return result;
}

Expand Down Expand Up @@ -238,13 +238,13 @@ private bool IsGenericTypeForMessage<T>()
{
bool ret = typeof(T).GetTypeInfo().IsGenericType &&
typeof(T).GetGenericTypeDefinition() == typeof(PNMessageResult<>);
logger.Trace($"typeof(T).GetGenericTypeDefinition() = {typeof(T).GetGenericTypeDefinition()}");
logger?.Trace($"typeof(T).GetGenericTypeDefinition() = {typeof(T).GetGenericTypeDefinition()}");
return ret;
}

private T DeserializeMessageToObjectBasedOnPlatform<T>(List<object> listObject)
{
logger.Debug("JsonNet Deserializing Messages data.");
logger?.Debug("JsonNet Deserializing Messages data.");
T ret = default(T);
Type dataType = typeof(T).GetTypeInfo().GenericTypeArguments[0];
Type generic = typeof(PNMessageResult<>);
Expand Down Expand Up @@ -319,7 +319,7 @@ private T DeserializeMessageToObjectBasedOnPlatform<T>(List<object> listObject)

ret = (T)Convert.ChangeType(message, specific, CultureInfo.InvariantCulture);
}
logger.Debug("JsonNet Deserialized Messages successfully.");
logger?.Debug("JsonNet Deserialized Messages successfully.");
return ret;
}

Expand Down
10 changes: 6 additions & 4 deletions src/Api/PubnubApi/Pubnub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,8 @@ public Pubnub(PNConfiguration config, IHttpClientService httpTransportService =
#if UNITY
OnCleanupCall += this.UnsubscribeAll<object>;
#endif
logger = InitializeLogger(config);
pubnubConfig[InstanceId].Logger = logger;
pubnubLog = config.PubnubLog;
savedSdkVerion = Version;
InstanceId = Guid.NewGuid().ToString();
Expand All @@ -1211,7 +1213,7 @@ public Pubnub(PNConfiguration config, IHttpClientService httpTransportService =
{
config.PresenceTimeout = 20;

config.Logger.Warn(
config.Logger?.Warn(
$"The PresenceTimeout cannot be less than 20, defaulting the value to 20. Please update the settings in your code.");
}

Expand All @@ -1226,7 +1228,7 @@ public Pubnub(PNConfiguration config, IHttpClientService httpTransportService =
IHttpClientService httpClientService =
httpTransportService ?? new HttpClientService(proxy: config.Proxy, configuration: config);
transportMiddleware = middleware ?? new Middleware(httpClientService, config, this, tokenManager);
logger.Debug(GetConfigurationLogString(config));
logger?.Debug(GetConfigurationLogString(config));
}

#if UNITY
Expand Down Expand Up @@ -1267,7 +1269,7 @@ private void CheckRequiredUserId(PNConfiguration config)
{
if (pubnubLog != null)
{
config.Logger.Warn($"PNConfiguration.Uuid or PNConfiguration.UserId is required to use the SDK.");
config.Logger?.Warn($"PNConfiguration.Uuid or PNConfiguration.UserId is required to use the SDK.");
}

throw new MissingMemberException("PNConfiguration.UserId is required to use the SDK");
Expand All @@ -1280,7 +1282,7 @@ private void CheckCryptoModuleUsageForLogging(PNConfiguration config)
{
if (config.CryptoModule != null && !string.IsNullOrEmpty(config.CipherKey) && config.CipherKey.Length > 0)
{
config.Logger.Debug($"CryptoModule takes precedence over CipherKey.");
config.Logger?.Debug($"CryptoModule takes precedence over CipherKey.");
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Api/PubnubApi/Security/SecureMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public List<object> HistoryDecodeDecryptLoop<T>(PNOperationType type, List<objec
{
status.AffectedChannelGroups.AddRange(channelGroups);
}
pubnubLog.Debug("Failed to decrypt message!Message might be not encrypted, Returning the original content as received ");
pubnubLog?.Debug("Failed to decrypt message!Message might be not encrypted, Returning the original content as received ");
}

object decodedMessage = jsonLib.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? jsonLib.SerializeToJsonString(element) : decryptMessage);
Expand Down Expand Up @@ -154,7 +154,7 @@ public List<object> FetchHistoryDecodeDecryptLoop<T>(PNOperationType type, Dicti
{
status.AffectedChannelGroups.AddRange(channelGroups);
}
pubnubLog.Debug("Failed to decrypt message!\nMessage might be not encrypted, returning as it is");
pubnubLog?.Debug("Failed to decrypt message!\nMessage might be not encrypted, returning as it is");
#endregion
}
object decodedMessage = jsonLib.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? jsonLib.SerializeToJsonString(kvpValue.Value) : decryptMessage);
Expand Down
Loading

0 comments on commit 164a41f

Please sign in to comment.