[英]Have log4net use application config file for configuration data
我想在我的application.config文件中存儲log4net配置數據。 根據我對文檔的理解,我做了以下工作:
添加對log4net.dll的引用
在AssemblyInfo.cs中添加以下行:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
按如下方式初始化記錄器:
private static readonly ILog log = LogManager.GetLogger(typeof(frmWizard));
我的app.config中有以下代碼:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
但是,當我運行該應用程序時,我在控制台上收到以下錯誤:
沒有找到名為[Consoleappender]的追加器。
如何讓log4net從配置文件中讀取設置?
謝謝!
在configSections元素中的app.config中添加一行
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
然后添加log4Net部分,但委托給其他地方的實際log4Net配置文件......
<log4net configSource="Config\Log4Net.config" />
在您的應用程序代碼中,當您創建日志時,請寫入
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
從問題中顯示的配置中只配置了一個appender,它被命名為“EventLogAppender”。 但是在root的配置中,作者引用了名為“ConsoleAppender”的appender,因此出現了錯誤消息。
您是否嘗試過為app.config添加configsection
處理程序? 例如
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
我完全支持@Charles Bretana的回答。 但是,如果它不起作用,請確保只有一個<section>
元素,並且configSections
是根元素的第一個子元素 :
configsections
必須是app.Config
配置后的第一個元素:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
<!-- add log 4 net config !-->
<!-- add others e.g. <startup> !-->
</configuration>
所有appender名稱必須反映在根部分中。
在您的情況下,appender名稱是EventLogAppender但在<root> <appender-ref ..
部分中它被命名為ConsoleAppender 。 他們需要匹配。
您可以在日志配置中添加多個appender,但需要在<root>
部分注冊每個appender。
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />
您還可以參考有關配置log4net的apache 文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.