Created
October 13, 2014 14:19
-
-
Save tonyjoanes/218a79435060c706fba3 to your computer and use it in GitHub Desktop.
Logging Aspect Interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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();