0

My solution has multiple projects. I have this below log wrapper class in a class library project. The dll of class library is referred in other projects so i can get use of this wrapper class.

But I coudnt access the _Logger or _Log in my other projects to pass the data to write to log. What am i missing here ?

    public class LoggerManager
{
    public static LoggerManager _Logger;
    public static ILog _log;
    public LoggerManager()
    {
        Init();
    }

    public static LoggerManager Instance
    {
        get
        {
            if (_Logger == null)
            {
                _Logger = new LoggerManager();
            }
            return _Logger;
        }
    }

    private void Init()
    {
        _log = LogManager.GetLogger(typeof(Program));
        XmlConfigurator.Configure();
    }

    public void Error(Exception ex, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
    {
        if (_log == null)
        {
            Init();
        }
        _log.Error(string.Format("Error from Method : {0} in file {1} at line {2}", memberName, filePath, lineNumber), ex);
    } 
}
Anuya
  • 8,082
  • 49
  • 137
  • 222
  • This won't fix your problem but why are you using this wrappen in the first case? – Mighty Badaboom Oct 04 '18 at 10:31
  • 2
    Why do you expose the underlying logger to the outside, when you actually want to wrap it? But anyway: can you please elaborate on "I couldn´t access `_Logger`? From the code above I can´t see why `LoggerManager.GetInstance()._Logger` shouldn´t work. – MakePeaceGreatAgain Oct 04 '18 at 10:31
  • @HimBromBeere it doesn't work because [static members cannot be accessed with an instance reference (in C#)](https://stackoverflow.com/a/1100023/43846) – stuartd Oct 04 '18 at 14:19

1 Answers1

1

Make sure you are trying to access the static variables like this:

LoggerManager._log or LoggerManager.Logger

Rather than through your instance:

var a = new LoggerManager()
a._log; // this wont work as the instance doesn't know about the static variables!

Seems like a strange wrapper when you are trying to access public static variables though. Would it be better to privatise them and make them available through your instance via a property? Such as:

public class LoggerManager
{
    private static LoggerManager _logger;
    private static ILog _log;

    public LoggerManager Logger => LoggerManager._logger;
    public ILog LogInstance => LoggerManager._log;

    // rest of your code...

}

Or maybe you could take a look at having a singleton class instead.

Rob
  • 6,819
  • 17
  • 71
  • 131