1

i created a global action filter to measure action execution time based on this answer Measure Time Invoking ASP.NET MVC Controller Actions

i want to log the results using log4net. i want to know if creating a logguer for each invocation has a performance impact. i have a static instance of ILog inside each of my controllers defined as below

private static ILog logger = log4net.LogManager.GetLogger(typeof(CompteController));

can i access it directly inside the action filter?

or is there a better way to do it?

Community
  • 1
  • 1
Souhaieb Besbes
  • 1,485
  • 17
  • 30
  • I have used this same approach before. Honestly, I don't see a REAL impact although you will technically incur "some". If you are worried about it you can leverage a "fire and forget" logging approach so that it does not slow down execution of your code when logging. – Jerrod Horton Feb 02 '16 at 16:45
  • You could create a singleton class that is instantiated when the application starts (global.asax or startup.cs) and then you only incur the instantiation cost only once? – FrankO Feb 02 '16 at 17:30
  • @FrankO I need to have the logger created with the type of the controller class – Souhaieb Besbes Feb 03 '16 at 09:36

2 Answers2

0

You could access the controller type within the action filter and instantiate the logger with the controller type (typeof(filterContext.Controller.GetType())). If you create a singleton and assign each new controller type logger in an array/collection, you should be able to access it on later requests.

If the logger for the controller does not exist within the singleton, then create a new one at that time. The cost of instantiating the new logger still exists but only when a new one is created.

FrankO
  • 2,522
  • 6
  • 24
  • 34
0

What I did to reduce logger overhead is create a single static logger for the whole application inside Global.asax.cs

public static ILog logger = LogManager.GetLogger(typeof(MvcApplication));
Souhaieb Besbes
  • 1,485
  • 17
  • 30