Can you configure log4net in code instead of using a config file?

后端 未结 6 1203
日久生厌
日久生厌 2020-11-28 01:20

I understand why log4net uses app.config files for setting up logging - so you can easily change how information is logged without needing to recompile your cod

6条回答
  •  遥遥无期
    2020-11-28 01:50

    FINAL SOLUTION:1

    For anyone who may stumble upon this in the future, here is what I did. I made the static class below:

    using log4net;
    using log4net.Repository.Hierarchy;
    using log4net.Core;
    using log4net.Appender;
    using log4net.Layout;
    
    namespace Spectrum.Logging
    {
        public class Logger
        {
            public static void Setup()
            {
                Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
    
                PatternLayout patternLayout = new PatternLayout();
                patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
                patternLayout.ActivateOptions();
    
                RollingFileAppender roller = new RollingFileAppender();
                roller.AppendToFile = false;
                roller.File = @"Logs\EventLog.txt";
                roller.Layout = patternLayout;
                roller.MaxSizeRollBackups = 5;
                roller.MaximumFileSize = "1GB";
                roller.RollingStyle = RollingFileAppender.RollingMode.Size;
                roller.StaticLogFileName = true;            
                roller.ActivateOptions();
                hierarchy.Root.AddAppender(roller);
    
                MemoryAppender memory = new MemoryAppender();
                memory.ActivateOptions();
                hierarchy.Root.AddAppender(memory);
    
                hierarchy.Root.Level = Level.Info;
                hierarchy.Configured = true;
            }
        }
    }
    

    And then all I had to do was replace the code where I called the XML file with the following call:

    //XmlConfigurator.Configure(new FileInfo("app.config")); // Not needed anymore
    Logger.Setup();
    

    1(this answer was edited into the question by the OP, I took the liberty to make it a community answer, see here why)

提交回复
热议问题