The following i would use in Logging code. Its a simple Idea, you log the error with and add what function went wrong.
Here is the function:
/// <summary>
/// Gets the Actal calling function.
/// B -> C(string) -> C()
/// will return B as C(String) is the
/// overloaded function. and not required
/// </summary>
/// <returns>Returns the Calling function, not the overloaded one.</returns>
public static StackFrame GetCallingMethod()
{
string current = new StackFrame(1, false).GetMethod().Name;
int FrameNumber = 1;
StackTrace st = new StackTrace(true);
StackFrame sf;
while (FrameNumber < st.FrameCount) {
FrameNumber += 1;
sf = st.GetFrame(FrameNumber);
if (!current.Equals(sf.GetMethod().Name)) {
return sf;
}
}
return null;
}
Now you may say, will i can get the calling method in one line of code!. well sure you can, but this is a bit more than that. It considers overloaded methods.
For example:
A simple logging function, where the coder has 2 overloads to choose from.
/// <summary>
/// norammly will log out to a Database
/// </summary>
/// <param name="ex">exception to log</param>
/// <param name="rethrow">indecate if the log should re
/// throw the execption</param>
static void LoggingFunction(Exception ex, bool rethrow)
{
StackFrame stackFrame = GetCallingMethod();
string callingFunction = stackFrame.GetMethod().Name;
string log =
string.Format(
"Function: {0} failed, with the following message\n{1}",
callingFunction, ex.Message);
Console.WriteLine(log);
if(rethrow)
throw ex;
}
/// <summary>
/// this will silently log an error, the
/// exception will not be rethrown
/// </summary>
/// <param name="ex">the exception to log</param>
static void LoggingFunction(Exception ex)
{
LoggingFunction(ex, false);
}
The second logging functions calls the first, passing in the rethow param. Also note that the first function is the only one which has the GetCallingMethod() call.
finally here is a fuction which uses the logging in case it fails (Ok this will fail every time, but use your imagination)
/// <summary>
/// the main overload
/// </summary>
/// <param name="name"></param>
static void WriteHelloWorld(string name)
{
try
{
//this would normally work
//but for this test i will throw an error:
Console.WriteLine("Hello :" + name);
throw new SystemException("something when wrong!");
}
catch(Exception ex)
{
LoggingFunction(ex);
}
}
When this WriteHelloWorld function is called, it fails calling the second logging function, which calls the first logging function. And this then logs out to the screen, giving the correct name of the function which failed, and called the logging functions.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5