Windows store app .NET GetCurrentMethod().DeclaringType alternative

quite stuck with this one... I have this problem where we are using log4Net in a Unity project for building a Windows store app. log4Net needs either the classes type or name (as string) which declared the logger. Since Windows store .NET is modified it does not have the usual method like GetCurrentMethod()... I checked around and so far it is hopeless:

The usual way is this

public sealed class SomeClassController : ApiController
{
    private static readonly ILog Log = 
        LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
...

How to get method name win 8 app - solutions provided here do not work, because the attribute [CallerMememberName] return the caller (not the declarer). The func(Expression expression) method does not work because it only works if used inside a method, but not as a class field (which is exactly the case in log4Net).

Another possibility was to use StackFrame, but "luckily" the Windows store does not support it either, the only way to get to the StackTrace is to through an exception, which is not an option because 1. Is is really slow 2. All exception throwing has to be removed in Unity production.

And simple solutions like GetType() do not work, because if there are inherited classes they get overriden. More here - http://rundevrun.blogspot.lt/2012/11/gettype-vs-methodbasegetcurrentmethodde.html

I am running out of option, is there no way to get the DeclaringType, when used in a class field???

Jon Skeet
people
quotationmark

Just use typeof instead - it's much simpler, and doesn't require any framework support:

public sealed class SomeClassController : ApiController
{
    private static readonly ILog Log = 
        LoggerManager.GetLogger(typeof(SomeClassController));
    ...
}

The only downside is that if you copy and paste that elsewhere, you'll end up logging with the wrong class. You could mitigate that by:

  • Writing a Roslyn code analyzer (or similar) to spot the problem
  • Being careful in code review
  • Have a prerelease process step of "Find all calls to LoggerManager.GetLogger and review them"

people

See more on this question at Stackoverflow