Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LogHandler is shared between multiple AblyRealtime instances #1250

Open
palashjhabak opened this issue Aug 2, 2023 · 7 comments
Open

LogHandler is shared between multiple AblyRealtime instances #1250

palashjhabak opened this issue Aug 2, 2023 · 7 comments
Assignees

Comments

@palashjhabak
Copy link

palashjhabak commented Aug 2, 2023

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.

Logger.LoggerSink = options.LogHandler;

┆Issue is synchronized with this Jira Task by Unito

@sync-by-unito
Copy link

sync-by-unito bot commented Aug 2, 2023

➤ Automation for Jira commented:

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

@sacOO7
Copy link
Collaborator

sacOO7 commented Aug 2, 2023

@palashjhabak let me check on this

@sacOO7
Copy link
Collaborator

sacOO7 commented Aug 2, 2023

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

@sacOO7
Copy link
Collaborator

sacOO7 commented Aug 2, 2023

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
Copy link
Author

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
Copy link
Collaborator

sacOO7 commented Aug 3, 2023

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

@palashjhabak
Copy link
Author

Perfect. Appreciate your quick response and even quicker PR.

Thanks a lot. Cheers.

@sacOO7 sacOO7 self-assigned this Aug 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

2 participants