I reviewed and agreed with all suggestions. But wanted to share one generic implementation for execution time logger where we do not want to implement Stopwatch logic multiple times but still wants to measure execution time for multiple methods.
The main reason for not to implement logger in generic way is - method execution is in between stopwatch.Start() and stopwatch.Stop() also we may require method result after the execution for further processing.
So to tackle this issue I created following sample implementation where Execution time is logged separately without mixing it with actual method flow.
public static class Helper
{
public static T Time<T>(Func<T> method, ILogger log)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = method();
stopwatch.Stop();
log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds));
return result;
}
}
public class Arithmatic
{
private ILogger _log;
public Arithmatic(ILogger log)//Inject Dependency
{
_log = log;
}
public void Calculate(int a, int b)
{
try
{
Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging
Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging
}
catch (Exception ex)
{
_log.Error(ex.Message, ex);
}
}
private string AddNumber(int a, int b)
{
return "Sum is:" + (a + b);
}
private string SubtractNumber(int a, int b)
{
return "Subtraction is:" + (a - b);
}
}
public class Log : ILogger
{
public void Info(string message)
{
Console.WriteLine(message);
}
public void Error(string message, Exception ex)
{
Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace);
}
}
public interface ILogger
{
void Info(string message);
void Error(string message, Exception ex);
}
Calling Part:
static void Main()
{
ILogger log = new Log();
Arithmatic obj = new Arithmatic(log);
obj.Calculate(10, 3);
Console.ReadLine();
}