ably / ably-dotnet

.NET, MAUI, Xamarin, Mono and Unity client library SDK for Ably realtime messaging service
https://ably.com/download
Apache License 2.0
45 stars 22 forks source link

LogHandler is shared between multiple AblyRealtime instances #1250

Open palashjhabak opened 1 year ago

palashjhabak commented 1 year ago

I think if I am implementing a custom logging handler, I might want to have AblyRealtime instance-specific things that I would want to log using the custom log handler.

Currenlty since the AblyRealtime is instantiated with a static DefaultLogger Handler, and even if I set a custom loghandler instance through client option, it does not set the Logger property to the custom instance, but it sets the property Logger.Loggersink to the handler, which makes the LoggerSink to be the last set logger sink for all the AblyRealTime instance.

https://github.com/ably/ably-dotnet/blob/d7abbdea6869dca81d76fa2fa9f82b3323439f57/src/IO.Ably.Shared/AblyRealtime.cs#L63

┆Issue is synchronized with this Jira Task by Unito

sync-by-unito[bot] commented 1 year ago

➤ Automation for Jira commented:

The link to the corresponding Jira issue is https://ably.atlassian.net/browse/SDK-3770

sacOO7 commented 1 year ago

@palashjhabak let me check on this

sacOO7 commented 1 year ago

@palashjhabak I have created a PR to fix this issue, we should have the fix merged by tomorrow 👍

sacOO7 commented 1 year ago

For the time being, you can pass additional clientOption -> Logger and pass instance of below class

    internal class CustomLogger : ILogger
    {
        /// <summary>Maximum level to log.</summary>
        /// <remarks>E.g. set to LogLevel.Warning to have only errors and warnings in the log.</remarks>
        public LogLevel LogLevel { get; set; }

        public ILoggerSink LoggerSink { get; set; }

        public bool IsDebug => LogLevel == LogLevel.Debug;

        private Func<DateTimeOffset> Now { get; }

        public IDisposable CreateDisposableLoggingContext(ILoggerSink loggerSink)
        {
            ILoggerSink oldLoggerSink = LoggerSink;
            LoggerSink = loggerSink;
            return new ActionOnDispose(() => LoggerSink = oldLoggerSink);
        }

        /// <summary>Log an error message.</summary>
        public void Error(string message, Exception ex)
        {
            Message(LogLevel.Error, $"{message} {GetExceptionDetails(ex)}");
        }

        /// <summary>Log an error message.</summary>
        public void Error(string message, params object[] args)
        {
            Message(LogLevel.Error, message, args);
        }

        /// <summary>Log a warning message.</summary>
        public void Warning(string message, params object[] args)
        {
            Message(LogLevel.Warning, message, args);
        }

        /// <summary>Log a debug message.</summary>
        public void Debug(string message, params object[] args)
        {
            Message(LogLevel.Debug, message, args);
        }

        private void Message(LogLevel level, string message, params object[] args)
        {
            try
            {
                ILoggerSink loggerSink = LoggerSink;
                if (LogLevel == LogLevel.None || level < LogLevel || loggerSink == null)
                {
                    return;
                }

                var timeStamp = GetLogMessagePrefix();
                if (args == null || args.Length == 0)
                {
                    loggerSink.LogEvent(level, timeStamp + " " + message);
                }
                else
                {
                    loggerSink.LogEvent(level, timeStamp + " " + string.Format(message, args));
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"Error logging message. Error: {e.Message}");
            }
        }

        private string GetLogMessagePrefix()
        {
            var timeStamp = Now().ToString("hh:mm:ss.fff");
            return $"{timeStamp}";
        }

        /// <summary>Produce long multiline string with the details about the exception, including inner exceptions, if any.</summary>
        private static string GetExceptionDetails(Exception ex)
        {
            try
            {
                if (ex == null)
                {
                    return "No exception information";
                }

                var message = new StringBuilder();

                if (ex is AblyException ablyException)
                {
                    message.AppendLine($"Error code: {ablyException.ErrorInfo.Code}")
                        .AppendLine($"Status code: {ablyException.ErrorInfo.StatusCode}")
                        .AppendLine($"Reason: {ablyException.ErrorInfo.Message}");
                }

                message.AppendLine(ex.Message)
                    .AppendLine(ex.StackTrace);

                if (ex.InnerException != null)
                {
                    message.AppendLine("Inner exception:")
                        .AppendLine(GetExceptionDetails(ex.InnerException));
                }

                return message.ToString();
            }
            catch (Exception e)
            {
                return $"Error getting exception details. Error: {e.Message}";
            }
        }
    }
palashjhabak commented 1 year ago

For the time being, you can pass additional clientOption -> Logger and pass instance of below class

    internal class CustomLogger : ILogger
    {
        /// <summary>Maximum level to log.</summary>
        /// <remarks>E.g. set to LogLevel.Warning to have only errors and warnings in the log.</remarks>
        public LogLevel LogLevel { get; set; }

        public ILoggerSink LoggerSink { get; set; }

        public bool IsDebug => LogLevel == LogLevel.Debug;

        private Func<DateTimeOffset> Now { get; }

        public IDisposable CreateDisposableLoggingContext(ILoggerSink loggerSink)
        {
            ILoggerSink oldLoggerSink = LoggerSink;
            LoggerSink = loggerSink;
            return new ActionOnDispose(() => LoggerSink = oldLoggerSink);
        }

        /// <summary>Log an error message.</summary>
        public void Error(string message, Exception ex)
        {
            Message(LogLevel.Error, $"{message} {GetExceptionDetails(ex)}");
        }

        /// <summary>Log an error message.</summary>
        public void Error(string message, params object[] args)
        {
            Message(LogLevel.Error, message, args);
        }

        /// <summary>Log a warning message.</summary>
        public void Warning(string message, params object[] args)
        {
            Message(LogLevel.Warning, message, args);
        }

        /// <summary>Log a debug message.</summary>
        public void Debug(string message, params object[] args)
        {
            Message(LogLevel.Debug, message, args);
        }

        private void Message(LogLevel level, string message, params object[] args)
        {
            try
            {
                ILoggerSink loggerSink = LoggerSink;
                if (LogLevel == LogLevel.None || level < LogLevel || loggerSink == null)
                {
                    return;
                }

                var timeStamp = GetLogMessagePrefix();
                if (args == null || args.Length == 0)
                {
                    loggerSink.LogEvent(level, timeStamp + " " + message);
                }
                else
                {
                    loggerSink.LogEvent(level, timeStamp + " " + string.Format(message, args));
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"Error logging message. Error: {e.Message}");
            }
        }

        private string GetLogMessagePrefix()
        {
            var timeStamp = Now().ToString("hh:mm:ss.fff");
            return $"{timeStamp}";
        }

        /// <summary>Produce long multiline string with the details about the exception, including inner exceptions, if any.</summary>
        private static string GetExceptionDetails(Exception ex)
        {
            try
            {
                if (ex == null)
                {
                    return "No exception information";
                }

                var message = new StringBuilder();

                if (ex is AblyException ablyException)
                {
                    message.AppendLine($"Error code: {ablyException.ErrorInfo.Code}")
                        .AppendLine($"Status code: {ablyException.ErrorInfo.StatusCode}")
                        .AppendLine($"Reason: {ablyException.ErrorInfo.Message}");
                }

                message.AppendLine(ex.Message)
                    .AppendLine(ex.StackTrace);

                if (ex.InnerException != null)
                {
                    message.AppendLine("Inner exception:")
                        .AppendLine(GetExceptionDetails(ex.InnerException));
                }

                return message.ToString();
            }
            catch (Exception e)
            {
                return $"Error getting exception details. Error: {e.Message}";
            }
        }
    }

I think Logger is set to internal in the ClientOption class

sacOO7 commented 1 year ago

Yeah, I think the fix should be available once we merge the PR 👍

palashjhabak commented 1 year ago

Perfect. Appreciate your quick response and even quicker PR.

Thanks a lot. Cheers.