Skip to content

Instantly share code, notes, and snippets.

@tonyjoanes
Created October 13, 2014 14:19
Show Gist options
  • Save tonyjoanes/218a79435060c706fba3 to your computer and use it in GitHub Desktop.
Save tonyjoanes/218a79435060c706fba3 to your computer and use it in GitHub Desktop.
Logging Aspect Interceptor
public class LoggingAspect : IInterceptor
{
private readonly ILogger logger;
private readonly Stopwatch stopwatch;
public LoggingAspect(ILogger logger)
{
this.logger = logger;
this.stopwatch = new Stopwatch();
}
public void Intercept(IInvocation invocation)
{
var parameterNames = invocation.Request.Method.GetParameters().Select(p => p.Name).ToList();
var parameterValues = invocation.Request.Arguments;
var message = new StringBuilder();
message.Append(string.Format("~Method '{0}.{1}'~Parameters ",invocation.Request.Target.GetType().Name, invocation.Request.Method.Name));
GetParameterInformation(parameterNames, parameterValues, message);
message.Append("~");
this.stopwatch.Start();
invocation.Proceed();
this.stopwatch.Stop();
message.Append(string.Format("~ {0}", this.stopwatch.ElapsedMilliseconds));
this.logger.LogInfo(message.ToString());
this.stopwatch.Reset();
}
private static void GetParameterInformation(IList<string> parameterNames, IList<object> parameterValues, StringBuilder message)
{
for (var index = 0; index < parameterNames.Count; index++)
{
var name = parameterNames[index];
var value = parameterValues[index];
message.Append(string.Format("<{0}>:<{1}>,", name, value));
}
}
}
@tonyjoanes
Copy link
Author

The following using statements are required:
using Ninject.Extensions.Interception.Infrastructure.Language;
using Ninject.Modules;

This is also required Ninject.Extensions.Interception.DynamicProxy

You can then apply interceptor for a service using .Intercept().With();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment