0

Currently , I am capturing execution time of each API using log4net and explicitly mentioning the start time and end time at the beginning and end of each API and writing into log file, as below

[HttpGet]
Public IHttpActionResult GetProducts()
{
    Log.info("API Execution Started at " + DateTime.Now());

    Var Products = UnitOfWork.GenericRepo.GetProducts();

    Log.Info("API Execution Completed at "+ DateTime.Now());

    Return Ok(Products);
}

Is there a better way to capture the execution time of each API and write that into a log file ? Also, Please provide me an insight on how to capture Tracing information of all APIs and writing that into different log files. For Example , Execution time of each API should be written into "ExecutionLog.txt" and Tracing infomration into "TracingLog.txt". I should also be able to enable or disable this features during run time.

Thanks in advance

alphacoder
  • 553
  • 2
  • 9
  • 21
  • Possible duplicate of [Measure Time Invoking ASP.NET MVC Controller Actions](http://stackoverflow.com/questions/11353155/measure-time-invoking-asp-net-mvc-controller-actions) – mongesh madhavan Jun 14 '16 at 08:18
  • Edited this to reflect the question in detail, other post does not provide more insight on achieving this . – alphacoder Jun 14 '16 at 15:18

3 Answers3

1

Use Stopwatch from System.Diagnostics namespace

see this for an example Example

MSDN

Ashley John
  • 2,379
  • 2
  • 21
  • 36
1

@Mahesh, You don't need to write it in each API. You can use ActionFIlter and ResultFilter and write a single code block to trace all actions in your API

Have a look at this https://jmperezperez.com/tracking-action-execution-time-in-asp-net-mvc/

mongesh madhavan
  • 583
  • 4
  • 16
0

In, System.Diagnostics namespace, you have a class named StopWatch. You can use this for checking function execution time. Use the Start() and Stop() methods for finding the total execution time.

Here is a simple example taken from dotnet pearl website

Stopwatch stopwatch = new Stopwatch();

// Begin timing.
stopwatch.Start();

// Do something.
for (int i = 0; i < 1000; i++)
{
    Thread.Sleep(1);
}

// Stop timing.
stopwatch.Stop();

// Write result.
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
vivek
  • 1,595
  • 2
  • 18
  • 35