ServiceStack 4.5以编程方式配置log4net [英] ServiceStack 4.5 configure log4net programmatically
问题描述
我正在使用ServiceStack 4.5启动一个新项目.有什么方法可以通过编程方式配置log4net?在我找到的文档中
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);
我将其添加到AppHost类的构造函数中.但是,这似乎是假设您将配置放入App.config文件中(我正在Windows服务上进行自我托管).
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).
在其他一些项目中,我编写了一个单例,然后使用Log4Net API进行配置:
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);
}
由于我使用了多个日志,所以追加程序etd并想关闭NHibernate日志记录(我将NHibernate 4用作ORM)等.我发现用C#进行配置比使用XML更方便.
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.
是否可以将其与ServiceStack挂钩,还是最好直接使用Log4Net?
Is it possible to hook this in with ServiceStack or do I better use Log4Net directly?
推荐答案
默认的ServiceStack Log4Net适配器不允许您注入已配置的Log4Net实例,但是适配器类很容易复制和修改,仅在这2个文件中基本上只是将呼叫转发到Log4Net:
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
这篇关于ServiceStack 4.5以编程方式配置log4net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!