ServiceStack 4.5 configure log4net programmatically

眉间皱痕 提交于 2019-12-11 08:11:46

问题


I am starting a new project with ServiceStack 4.5. Is there any way to configure log4net programmatically? In the documentation I found

LogManager.LogFactory = new Log4NetFactory(configureLog4Net: true); 

I added this to the constructor of the AppHost class. However this seems to assume that you put the configuration to the App.config file (I am doing self-hosting on a windows service).

In some other projects I wrote a singleton and then used the Log4Net API to do the configuration:

   private static void CreateFileAppender(ref Logger bedInventoryLogger, string logFilePath, Level logLevel, int maxFileSizeInMb, bool filterNh)
    {
        var filePatternLayout = new PatternLayout
        {
            ConversionPattern = "%date; [%thread]; %-5level; %logger; [%type{1}.%method]; - %message%newline"
        };
        filePatternLayout.ActivateOptions();
        var bediLogFileAppender = new RollingFileAppender
        {
            File = logFilePath,
            AppendToFile = true,
            MaximumFileSize = $"{maxFileSizeInMb}MB",
            MaxSizeRollBackups = 5,
            RollingStyle = RollingFileAppender.RollingMode.Size,
            LockingModel = new FileAppender.MinimalLock(),
            Layout = filePatternLayout,
            StaticLogFileName = true,
            Threshold = logLevel
        };
        if (filterNh)
        {
            bediLogFileAppender.AddFilter(new LoggerMatchFilter
            {
                LoggerToMatch = "NHibernate",
                AcceptOnMatch = false
            });
            bediLogFileAppender.AddFilter(new LoggerMatchFilter
            {
                LoggerToMatch = "NHibernate.SQL",
                AcceptOnMatch = false
            });
            bediLogFileAppender.AddFilter(new LoggerMatchFilter
            {
                LoggerToMatch = "FluentNHibernate",
                AcceptOnMatch = false
            });
        }
        bediLogFileAppender.ActivateOptions();
        bedInventoryLogger.AddAppender(bediLogFileAppender);
    }

Since I used several logs, appenders etd and wanted to turn off NHibernate logging (I am using NHibernate 4 as ORM) etc. I found it more convenient to do configuration in C# than in XML.

Is it possible to hook this in with ServiceStack or do I better use Log4Net directly?


回答1:


The default ServiceStack Log4Net adapter doesn't allow you to inject a configured Log4Net instance however the adapter classes are easy to copy and modify which are just in this 2 files which basically just forward the calls to Log4Net:

  • Log4NetFactory.cs
  • Log4NetLogger.cs


来源:https://stackoverflow.com/questions/39753202/servicestack-4-5-configure-log4net-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!