Getting the class name

3k Views Asked by At

How to get the class-name with caller info attributes.

I strongly say a no to log the class name using reflection.

Was able to get the method name using the [CallerMemberName] like below:

        private void Log(string logMessage, [CallerMemberName]string callerName = null)
        {
            if (logger.IsDebugEnabled)
            {
                logger.DebugFormat("Executing Method = {1};{0}", logMessage, callerName);
            }
        }

How to log the class name here using Caller Info Attributes ?

2

There are 2 best solutions below

0
On BEST ANSWER

You can't there is no attribute available that does that. However because Log is private no external classes could call the function so you already know which class called it.

public SomeClass
{

    //(snip)

    private void Log(string logMessage, [CallerMemberName]string callerName = null)
    {

        if (logger.IsDebugEnabled)
        {
            string className = typeof(SomeClass).Name;

            logger.DebugFormat("Executing Method = {1};{2}.{0}", logMessage, callerName, className);
        }
    }
}
2
On

First of all, the method is private so only the current class would be using it, in which case this can be found by using the typeof(T).FullName or typeof(T).Name property.

What you could also try here is to find out the class name from the stack frame programatically which would work for other classes if the method was public, as shown below:

private void Log(string logMessage)
{
  StackFrame frame = new StackFrame(1, false);
  MethodBase method = frame.GetMethod();
  Type declaringType = method.DeclaringType;

  // Log declaringType.FullName or other property
}

You can find more information on the StackFrame here and the MethodBase here

The other way you could do this is have a Type parameter on the method to log, and pass in the Type that you want to be logged, however the method would need to be public if it is to be called from outside this class:

public void Log(string logMessage, Type classType)
{
  // Log message and class name
}

Hope this helps.