Log4Net错误:Log4Net中基于文件的登录不起作用



我正在尝试将log4net记录器实现到我的WPF应用程序。基于文件的登录对我不起作用。

我读了很多其他的问题和答案,但我还没能解决它。。。这就是我得到的错误:

log4net:ERROR Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />

log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="console" />
<appender-ref ref="file" />      
</root>
<appender name="console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file value="${LocalAppData}//myapp//Logs//myappplog.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender>  
</log4net>
</configuration>

Assemblyinfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

应用程序配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<log4net configSource="log4net.config" />
<entityFramework>

mainview.xaml.cs公共分部类mainview:UserControl{

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

public MainView()
{
InitializeComponent();
Getloaded();
}
public void Getloaded()
{
log4net.Config.XmlConfigurator.Configure();
try
{
log.Info("        =============  Started Application  =============        ");
}
catch(Exception ex)
{
}
}

您正在声明log4net,但没有添加它。这会导致.net引发该错误。您应该从配置文件中删除log4net节声明,并将配置文件名(log4net.config(传递到log4net.Config.XmlConfigurator.Configure("log4net.config");方法中,或者将log4net配置节直接添加到App.config中(<log4net configSource="log4net.config" />。我相信第二种方式对你来说是最好的。

以下是在这种情况下配置的样子。

<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />     
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<log4net configSource="log4net.config" />
...

最新更新