0

In VS 2010 I have a console app. The app references a Common dll that references log4net. This is a long running app that was recently modified to target x64 due to memory issues. Since the x64 change another issue has been introduced.

The app runs fine in debug mode and in release mode with F5. It will not run in release mode with CTRL F5 (i.e. without debugging).
The error is a NullReferenceException from within the common dll

The line attempts to call a static method on the LogManager (log4net).

I am using the latest version of log4net

There is no DEBUG specific code

   public static void LogError(Exception ex)
    {
        _log = LogManager.GetLogger(GetLoggerType()); //Fails on GetLogger 
        _log.Error(ex);
    }

    private static Type GetLoggerType()
    {
        var frame = new StackFrame(2);
        var method = frame.GetMethod();
        return method.DeclaringType;
    }
  • Show some code, it seems that the issue is in your code. Log4net is designed to fail without any exceptions. – Peter Jun 02 '14 at 12:38
  • Code added. The code is the same code that worked before changing the target to x64 and that works in debug mode. – user3698845 Jun 02 '14 at 13:18

1 Answers1

4

You problem is not in log4net. It is working fine, however:

    var frame = new StackFrame(2);
    var method = frame.GetMethod();
    return method.DeclaringType;

is not. In release mode this optimized and probably causing problems for that reason. Because your logerror method is depending on the logger name (declaringtype), you should just include it in the signature of the LogError method.

Maybe this will do for you if you do not wish add your declaringtype all the time:

public static string LogError(Exception ex, [CallerMemberName] string callerName = "")

You should have a look at this question:

stackframe-behaving-differently-in-release-mode

Community
  • 1
  • 1
Peter
  • 27,590
  • 8
  • 64
  • 84
  • This works: _log =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); But it gives me the Logger itself as a type. I will need to work out a way to go two up the stack to get the calling dll. thanks. What you say seems correct although not sure why it was ok in 32 bit. – user3698845 Jun 02 '14 at 13:33
  • Decorated GetLoggerType() with [MethodImpl(MethodImplOptions.NoInlining)] Works perfectly now. – user3698845 Jun 02 '14 at 13:47
  • @user3698845 32bit and 64bit are differently optimized. If they would be the same, you would not have to know what type you are building. – Peter Jun 02 '14 at 13:49