alphacoder
alphacoder

Reputation: 573

Identify execution time and Tracing of each API in ASP.NET WEB API and log to files using log4net using C#

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

Upvotes: 0

Views: 3244

Answers (3)

mongesh madhavan
mongesh madhavan

Reputation: 599

@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/

Upvotes: 1

vivek
vivek

Reputation: 1605

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);

Upvotes: 0

Ashley John
Ashley John

Reputation: 2453

Use Stopwatch from System.Diagnostics namespace

see this for an example Example

MSDN

Upvotes: 1

Related Questions