Skip to content

Instantly share code, notes, and snippets.

@joeybeninghove
Last active January 29, 2025 00:53
Show Gist options
  • Save joeybeninghove/aa827df928614d54ceba8a5a388e3901 to your computer and use it in GitHub Desktop.
Save joeybeninghove/aa827df928614d54ceba8a5a388e3901 to your computer and use it in GitHub Desktop.
Logging Abstraction Around Quantower
public interface ILogger
{
void Log(string message, LogLevel level = LogLevel.Info);
}
public class Logger : ILogger
{
private static readonly Lazy<Logger> instance = new(() => new Logger());
private ILogger underlyingLogger;
private Logger()
{
}
public static Logger Instance => instance.Value;
public static void Initialize(ILogger underlyingLogger)
{
if (Instance.underlyingLogger == null)
{
Instance.underlyingLogger = underlyingLogger ?? throw new ArgumentNullException(nameof(underlyingLogger));
}
else
{
throw new InvalidOperationException("Logger has already been initialized.");
}
}
public static void Reset()
{
Instance.underlyingLogger = null;
}
public void Log(string message, LogLevel level = LogLevel.Info)
{
if (underlyingLogger == null)
{
throw new InvalidOperationException("Logger has not been initialized.");
}
underlyingLogger.Log(message, level);
}
}
public class QuantowerLogger : ILogger
{
private readonly Strategy strategy;
private readonly MethodInfo? logMethod;
public QuantowerLogger(Strategy strategy)
{
this.strategy = strategy;
logMethod = strategy.GetType().GetMethod("Log", BindingFlags.Instance | BindingFlags.NonPublic);
if (logMethod == null)
throw new InvalidOperationException("Could not find Log method in strategy");
}
public void Log(string message, LogLevel level = LogLevel.Info)
{
var quantowerLevel = level switch
{
LogLevel.Info => StrategyLoggingLevel.Info,
LogLevel.Error => StrategyLoggingLevel.Error,
_ => StrategyLoggingLevel.Info
};
logMethod?.Invoke(strategy, [message, quantowerLevel]);
}
}
public class Strategy : TradingPlatform.BusinessLayer.Strategy
{
protected override void OnCreated()
{
Logger.Initialize(new QuantowerLogger(this));
}
protected override void OnRemove()
{
Logger.Reset();
}
}
// now from my own class, I can easily log messages to the strategy log window without couupling myself directly to the Quantower logger
public class MyOwnClass
{
public void SomeMethod()
{
Logger.Instance.Log("some super important message");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment