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

Optimize logger #3370

Open
wants to merge 8 commits into
base: v4-development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 62 additions & 28 deletions sdk/src/Core/Amazon.Runtime/Internal/Util/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,11 @@
* permissions and limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.ComponentModel;
using Amazon.Runtime;
using System.Linq;
using System.Threading;
using Amazon.Util.Internal;

namespace Amazon.Runtime.Internal.Util
Expand All @@ -31,9 +28,8 @@ namespace Amazon.Runtime.Internal.Util
/// </summary>
public class Logger : ILogger
{
private static IDictionary<Type, Logger> cachedLoggers = new Dictionary<Type, Logger>();
private static ConcurrentDictionary<Type, Lazy<Logger>> cachedLoggers = new ConcurrentDictionary<Type, Lazy<Logger>>();
private List<InternalLogger> loggers;
private static Logger emptyLogger = new Logger();

private Logger()
{
Expand All @@ -46,19 +42,20 @@ private Logger()
#endif
private Logger(Type type)
{
loggers = new List<InternalLogger>();

if(!InternalSDKUtils.IsRunningNativeAot())
{
loggers = new List<InternalLogger>(3);
#pragma warning disable
InternalLog4netLogger log4netLogger = new InternalLog4netLogger(type);
loggers.Add(log4netLogger);
loggers.Add(new InternalLog4netLogger(type));
#pragma warning restore
}
else
{
loggers = new List<InternalLogger>(2);
}

loggers.Add(new InternalConsoleLogger(type));
InternalSystemDiagnosticsLogger sdLogger = new InternalSystemDiagnosticsLogger(type);
loggers.Add(sdLogger);
loggers.Add(new InternalSystemDiagnosticsLogger(type));
ConfigureLoggers();
AWSConfigs.PropertyChanged += ConfigsChanged;
}
Expand All @@ -80,39 +77,76 @@ private void ConfigureLoggers()
il.IsEnabled = (logging & LoggingOptions.Console) == LoggingOptions.Console;
if (il is InternalSystemDiagnosticsLogger)
il.IsEnabled = (logging & LoggingOptions.SystemDiagnostics) == LoggingOptions.SystemDiagnostics;

if (!IsEnabled)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For all of these properties the last InternalLogger will overwrite the value on the Logger. If I understand the purpose the properties on the Logger should be true if any of the InternalLogger are true.

Copy link
Contributor Author

@danielmarbach danielmarbach Jul 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do suck at boolean logic and would probably fail any job interview 👯‍♂️

Isn't that exactly what it is doing? If the property is false it will check the property of the internal logger and set it to the corresponding value of the internal logger. If the internal logger is true it sets the property to true and subsequent checks don't need to look at the internal logger value anymore. If the property gets set to false the next iteration needs to check the value of the next internal logger. So if all are false it remains false. If one is true it will turn to true and subsequent checks omit toggling it. I wanted to avoid Any()

https://dotnetfiddle.net/Se39FX

{
IsEnabled = il.IsEnabled;
}
if (!IsErrorEnabled)
{
IsErrorEnabled = il.IsErrorEnabled;
}
if (!IsInfoEnabled)
{
IsInfoEnabled = il.IsInfoEnabled;
}
if (!IsDebugEnabled)
{
IsDebugEnabled = il.IsDebugEnabled;
}
}
}

#region Static accessor

public static Logger GetLogger(Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (type == null) throw new ArgumentNullException(nameof(type));

Logger l;
lock (cachedLoggers)
{
if (!cachedLoggers.TryGetValue(type, out l))
{
l = new Logger(type);
cachedLoggers[type] = l;
}
}
return l;
// Use a lazy initialization to ensure that we only create a logger for a given type once because
// the constructor does some heavy lifting including setting up event listeners.
var lazyLogger = cachedLoggers.GetOrAdd(type, static t => new Lazy<Logger>(() => new Logger(t)));
return lazyLogger.Value;
}

public static void ClearLoggerCache()
{
lock (cachedLoggers)
var newLoggerCache = new ConcurrentDictionary<Type, Lazy<Logger>>();
ConcurrentDictionary<Type, Lazy<Logger>> oldLoggerCache;

do
{
cachedLoggers = new Dictionary<Type, Logger>();
oldLoggerCache = cachedLoggers;
} while (Interlocked.CompareExchange(ref cachedLoggers, newLoggerCache, oldLoggerCache) != oldLoggerCache);

// Unregister all the loggers in the old cache
foreach (var item in oldLoggerCache ?? Enumerable.Empty<KeyValuePair<Type, Lazy<Logger>>>())
{
var lazyLogger = item.Value;
if (lazyLogger.IsValueCreated)
{
lazyLogger.Value.Unregister();
}
Comment on lines +123 to +129
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have realized the config change handler is never unregistered and effectively the old logger instances can still be rooted.

}
}

public static Logger EmptyLogger { get { return emptyLogger; } }
public static Logger EmptyLogger { get; } = new Logger();

#endregion

internal bool IsEnabled { get; private set; }

internal virtual bool IsErrorEnabled { get; private set; }

internal virtual bool IsDebugEnabled { get; private set; }

internal virtual bool IsInfoEnabled { get; private set; }

internal void Unregister()
{
AWSConfigs.PropertyChanged -= ConfigsChanged;
}

#region Logging methods

public void Flush()
Expand Down
14 changes: 9 additions & 5 deletions sdk/src/Core/Amazon.Util/AWSSDKUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -385,11 +385,15 @@ public static string CanonicalizeResourcePathV2(Uri endpoint, string resourcePat
string canonicalizedResourcePath = JoinResourcePathSegmentsV2(encodedSegments);

// Get the logger each time (it's cached) because we shouldn't store it in a static variable.
Logger.GetLogger(typeof(AWSSDKUtils)).DebugFormat("{0} encoded {1}{2} for canonicalization: {3}",
pathWasPreEncoded ? "Double" : "Single",
resourcePath,
endpoint == null ? "" : " with endpoint " + endpoint.AbsoluteUri,
canonicalizedResourcePath);
var logger = Logger.GetLogger(typeof(AWSSDKUtils));
if (logger.IsDebugEnabled)
{
logger.DebugFormat("{0} encoded {1}{2} for canonicalization: {3}",
pathWasPreEncoded ? "Double" : "Single",
resourcePath,
endpoint == null ? "" : $" with endpoint {endpoint.AbsoluteUri}",
canonicalizedResourcePath);
}

return canonicalizedResourcePath;
}
Expand Down