0

I am trying to get my current log4net logging level during runtime to display on my app's UI.

string strLogLevel = "";
strLogLevel = ((log4net.Repository.Hierarchy.Logger)mylogger.Logger).Level.ToString();

But every time this code runs I get the following error:

{"Object reference not set to an instance of an object."}

I'm positive that my logging is configured correctly, since I am generating logs. So what's going on?

ShowJX1990
  • 77
  • 2
  • 11
  • 2
    I would split the statements and see which one is null. For e.g., extract (log4net.Repository.Hierarchy.Logger)mylogger into a variable and see whether the conversion resulted in non-null or not. – sam Jan 22 '20 at 14:02
  • Either `mylogger` is null, or `mylogger.Logger` is null, or `.Level` is null. Use your debugger to figure out which is the case. –  Jan 22 '20 at 14:53

1 Answers1

0

It's hard to tell without seeing the calling context, but the general answer is here:

https://stackoverflow.com/a/4660186/4406646

Specific to log4net, depending on the configuration loggers can (and usually) have multiple levels configured. You also control what level is called with the methods described here:

https://logging.apache.org/log4net/release/sdk/html/Methods_T_log4net_ILog.htm

To get a string value related to level was used for a ILog method call, you could wrap the call like this:

MyLogger.cs

using System.Reflection;
using log4net;

namespace YourNamespace
{
    internal static class MyLogger
    {
        private static readonly ILog Logger =
                                 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        internal static string LogSomething()
        {
            Logger.Info("something");
            return "Info";
        }
    }
}

Elsewhere in YourNamespace

string strLogLevel  = MyLogger.LogSomething();
plr108
  • 1,201
  • 11
  • 16