There is one method and I want to see how much time is spent on its work. I do this through filters, but it's not entirely clear how they work:

Here is the method that we will test:

[TimeMetric( Name = nameof(ExcelToDataTable) )] public DataTable ExcelToDataTable() { // много кода } 

But the implementation of the filter yes counting imputation:

 public class TimeMetricAttribute: ActionFilterAttribute { // Имя метода который мы сичтаем public string Name { get; set; } private Stopwatch stopWatch; public TimeMetricAttribute() { Name = "Неизвестно"; stopWatch = new Stopwatch(); } public override void OnActionExecuting( ActionExecutingContext filterContext ) { stopWatch.Start(); } public override void OnActionExecuted( ActionExecutedContext filterContext ) { stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. string elapsedTime = String.Format( "{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10 ); // Ну тут временное решение, потом буду писать куда-нибуть в базу Debug.WriteLine( $"\n\n{Name}: RunTime {elapsedTime}\n"); } } 

I understand everything correctly about the filters or is it nonsense? The problem is that it does not work, the filter is apparently not called ...

Are the filters only applicable to the controller's methods, or can they be applied to their business logic methods?

If not, then is there any mechanism that allows to call some actions before calling the target method and after?

    1 answer 1

    You need to use the trace mechanism built in asp.net enter image description here Enabling this option will only affect .cs files, so for cshtml you will have to add the following:

     <system.diagnostics> <trace autoflush="true"> <listeners> <add name="textLogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="app.log" /> <remove name="Default" /> </listeners> </trace> </system.diagnostics> 

    Detailed help is available in MSDN: https://msdn.microsoft.com/ru-ru/library/bb386420(v=vs.100).aspx

    • It's not entirely clear how this solves my problem. The task is not to litter the code, to add attributes to spying on several methods. - Vasya Milovidov
    • You will see the operating time of absolutely all controllers. Then it remains only to parse from the logs. The following help indicates how to do the same thing not with the configuration, but with the code. You can write your attribute, which will weigh on the methods, and inside write to the trace log - Anton Shakalo
    • It seems to me that such an ASP.NET trace is convenient for debugging. And if I want to collect metrics in the production version? - Vasya Milovidov
    • You can do it in production, I see no problems here. Are you afraid that performance will fall? - Anton Shakalo
    • No, I'm afraid of this magic) - Vasya Milovidov