In production environment, it is not always possible to step through the compiled code using a debugger and thus we rely on error logs to provide insights into the potential causes of bugs. The location of the bug, which is provided by the stacktrace of the exception, is not always helpful in determining the reason of the exception as the exception might be caused by data. So it is desirable to log not only the location of the error but also the object and the related object’s states (e.g. the value of the variables, etc).
using System;
using System.Collections.Generic;
using System.Text;
public class Record
public string ObjName = string.Empty;
public string ObjColor = string.Empty;
public class Records
public List<Record> records = null;
public Records()
public override string ToString()
StringBuilder sb = new StringBuilder();
sb.Append(r.ToString());
sb.Append(Environment.NewLine);
}
}
}
As you can see in the code above, both Record and Records classes override the base ToString function and each outputs its member variables’ states.
To test our implemtation, consider the code below:
public void Test()
Records r = new Records();
try
r.records.Add(new Record("car", "red"));
r.records.Add(new Record("apple", "green"));
r.records.Add(new Record("sky", "blue"));
throw new Exception("This is a test");
}
catch (Exception e)
Console.WriteLine(e.StackTrace);
Console.WriteLine(r.ToString());
}
}
Her we purposefully threw an exception and the second line writes out the object (note, here is the place where logging function would be placed).
{car — red}