Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize log4net without xml file

I need to create a little wrapper for log4net package.

I also need to initialize the logger without using a xml config file (it's a requirement, there are already a lot of configuration files in this project).

I've written the MyLogger class, but when I run the program I don't see anything in the console.

I've tried to shrink the code in order to have a minimum example (I've removed my configuration file loading and some other thing).

At first I create the logger instance, I set the level to Trace, and then I add a AnsiColorTerminalAppender. Obviously there's something wrong or missing, but I can't understand what.

How can I fix my class in order to print the log message?

using log4net;

namespace MyProgram
{
  static class MyLogger
  {
    static ILog logger = null;

    public static void SetConfiguration()
    {
      logger = LogManager.GetLogger(typeof(MyLogger));
      var l = (log4net.Repository.Hierarchy.Logger)logger.Logger;
      l.Level = log4net.Core.Level.Trace;
      AddConsoleAppender();
    }

    public static void Debug(string message)
    {
      logger.Debug(message);
    }

    public static void Info(string message)
    {
      logger.Info(message);
    }

    // Others here

    static private void AddConsoleAppender()
    {
      var appender = new log4net.Appender.AnsiColorTerminalAppender
      {
        Threshold = log4net.Core.Level.Info
      };
      var l = (log4net.Repository.Hierarchy.Logger)logger.Logger;
      log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout
      {
        ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"
      };
      layout.ActivateOptions();
      appender.Name = "Console";
      appender.Layout = layout;
      appender.ActivateOptions();
      l.AddAppender(appender);
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      MyLogger.SetConfiguration();
      MyLogger.Info("Logger configuration loaded");
    }
  }
}
like image 270
Jepessen Avatar asked Dec 13 '17 14:12

Jepessen


1 Answers

If you are adding appenders without using of BasicConfigurator, you should manually set Configured property of Logger repository to true. Just add following line to the bottom of AddConsoleAppender() method:

static private void AddConsoleAppender()
{
    // ...
    var l = (log4net.Repository.Hierarchy.Logger)logger.Logger;
    // ...
    l.Repository.Configured = true;
}
like image 60
CodeFuller Avatar answered Nov 12 '22 07:11

CodeFuller