mercredi 9 janvier 2019

AOP Logging understanding

I have been working out how I can use Aspect Oriented Programming and have followed this tutorial as a start. I have got this working here so I have before and after method call logging. I then wanted to use that logger to do the rest of the logging we would normally do in and around the object in question. All I had to do for it to work was to change the last line of SetParameters from:

 _loggingScheduler = loggingScheduler ?? TaskScheduler.FromCurrentSynchronizationContext();

to

_loggingScheduler = loggingScheduler ?? TaskScheduler.Current;

Not sure why that worked for me but it does. Then I wanted to be able to use that Aspect/Decoration to do the rest of the logging we would require. So I added a Log Method to the aspect and used it accordingly:

public void Log(string level, string msg)
{
     Console.WriteLine($"{level} {DateTime.Now.ToString("s")} {msg}");
}

So just console logging for now. I used that method like this:

public static void Main(string[] args)
{
    var calculator = LoggingAdvice<ICalculator>.Create(
                              new Calculator(),
                              s => Console.WriteLine("Info: " + s),
                              s => Console.WriteLine("Error: " + s),
                              o => o?.ToString());

    var addition = calculator.Add(2, 2);
    ((LoggingAdvice<ICalculator>)calculator).Log("Info", $"The result of Add was {addition}");

    var subtraction = calculator.Subtract(10, 4);
    ((LoggingAdvice<ICalculator>)calculator).Log("Info", $"The result of Subtract was {subtraction}");



    Console.WriteLine($"Results: Add - {addition}, subtract - {subtraction}");
    Console.Read();
}

Which is, realistically, just a duplication of the LogAfter() functionality. What I thought I could achieve with this is to use the aspect for all of the logging I wanted which is:

  • Before and after method calls (tick)
  • Use it to log around the object (tick)
  • Log inside the Calculator (completely stuck on)

Now I am starting to circle round on myself and my understanding of what I am doing here is waning.

So my questions are:

  • What am i doing here - AOP, Decorator or Proxy pattern (probably a mix)
  • Can I use the aspect inside the decorated object
  • Do I still have to DI a logger into my classes for internal logging
  • How much of a violation is the Calculator cast

So basically I am being a little greedy here and want to use the aspect I have created to do all of my logging. Is this possible?

Aucun commentaire:

Enregistrer un commentaire