1

I am trying to make a Error Logging which has namespace info in it. but while I use static functions I can't get classes namespace (I can't use "this"). Any trick to handle this?

thank you in advance.

    public class Test
    {
        public static string Tester()
        {
            try
            {
                 //SOMETHING
            } 
            catch (Exception ex)
            {
                Error.DP.LogAdd(!!NAMESPACE HERE!!, ex.Message);
            }
        }
    }  
Mert
  • 6,432
  • 6
  • 32
  • 68
  • Could I ask you why? I think what it is much more useful to provide sort of identification to the logger (because it catches exception *somewhere* inside, but the catcher can be anywhere, in another class caller, or re-throwing, etc.). Something like `Log("Test A - to big value", exception);` – Sinatr Dec 02 '13 at 13:01
  • Thank you Micheal, this is exactly what I was looking for. SinaTr, for extra information can be used another field maybe. this field specifies which function gives the error. :) – Mert Dec 02 '13 at 13:08

2 Answers2

3

You can try to get namespace from inside Log function (which is pretty nut me think):

public class Test
{
    public static string Tester()
    {
        try
        {
             //SOMETHING
        } 
        catch (Exception exception)
        {
            Log(exception);
        }
    }

    public static void Log(Exception exception)
    {
           var namespace = new StackFrame(1).GetMethod().DeclaringType.Namespace;
           //MOREOFSOMETHING
    }
}  
Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • Thank you Sina, I am planing to use this in order to get all namespace with method name; new StackFrame(1).GetMethod().DeclaringType.Namespace + "." + new StackFrame(1).GetMethod().Name; – Mert Dec 02 '13 at 14:21
0

Following up on @Sinatr's Idea, you can get the name of the class using:

var NameOfClass = new StackFrame(1).GetMethod().DeclaringType.GetTypeInfo().AsType().FullName;
Avi Turner
  • 10,234
  • 7
  • 48
  • 75