What is the best way to get the class name calling my function?

  • Thread starter Thread starter Mike
  • Start date Start date
M

Mike

Hi All,

I have implemented some logging functionality in my program.

public void logwrite(string Msg)
{
System.Diagnostics.StackTrace st = new
System.Diagnostics.StackTrace(1);
System.Diagnostics.StackFrame sf = st.GetFrame(0);
//Get the name of the class and procedure that called us
string ClassName = sf.GetMethod().DeclaringType.Name + "." +
sf.GetMethod().Name;
Writetolog (ClassName + Msg, "c:\temp.txt");
}

So I would basically call logwrite ("Error Ocurred") from my Main
method and this would then output MyClass.Main - Error Ocurred to a
log file.

The trouble I am having is that System.Diagnostics.StackTrace st = new
System.Diagnostics.StackTrace(1); is very slow to execute and this is
causing a bottleneck when I have lots of activity.
Is there anyway of speeding this up short of passing the class name in
with the msg and doing away with the Stackframe class altogether.

Many Thanks,

Mike
 
Hi,

A possible solution would be to pass a second parameter of type object ,
use GetType() to get the type of it and then use FullName to get the fully
qualified name of it
like this:

public void logwrite(string Msg, object sender)
{
string ClassName = sender.GetType().FullName;
Writetolog (ClassName + Msg, "c:\temp.txt");
}

Now if you want also to get the method name you have only two options I can
think of:
1- Pass the method name as a third parameter
2- Use StackTrace as currently :(


Cheers,
 
Back
Top