-1

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 ?

InitLipton
  • 2,395
  • 5
  • 30
  • 47

2 Answers2

5

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.

Rob Aston
  • 816
  • 12
  • 19
  • `StackFrame` is not reliable when using release builds without a debugger attached. Things like method inlineing can make it look like the code exists somewhere else than where you think it exists. – Scott Chamberlain Jun 24 '14 at 16:28
  • That's true, it would need to be set to NoInlining for it to be reliable. I forgot this point - thanks. – Rob Aston Jun 24 '14 at 16:33
3

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);
        }
    }
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431