Log4Net error : "Failed to find configuration section log4net" - c#

I'm getting started with log4net.I'm working on a small console project in which i must implement this framework.
At the beginning i created a small console project to see how it works without any other code.
I managed to make it work properly.
Now i try to migrate all the code in my application and i get this error when i execute the .exe of my console application:
"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"/>
The code:
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
ILog log = log4net.LogManager.GetLogger(typeof(Program));
...
The app.config didn't exist yet so its content is the same as the test project i did:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="D:\WEB\SAI\log\nas\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
After some searches on internet, i added:
[assembly: log4net.Config.XmlConfigurator()]
to my AssemblyInfo.cs as it was suggested but the result is still the same...
Thanks in advance for your help

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

Related

log4net is not logging anything nor creating the file

I'm trying to configure log4net in my WPF application but I'm struggling to do so. I have read all the questions about it here but none resolved my issue. Find the code down below.
log4net NuGet version: 2.0.8
AssemblyInfo.cs
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="C:\Mylogs\Installer.log" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
MainWindow.xaml.cs
using log4net;
...
public partial class MainWindow
{
...
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
...
private void BtnChangeLocation_Click(object sender, RoutedEventArgs e)
{
...
Log.Debug("This is a Debug message");
Log.Info("This is a Info message");
Log.Warn("This is a Warning message");
Log.Error("This is an Error message");
Log.Fatal("This is a Fatal message");
}
}
When I run the application and click on the button (BtnChangeLocation_Click) no file is created, or even if I create the file manually, nothing is inserted into it. What could be the problem?
I'd suggest to read this: Log4net Tutorial.
There you'll find 14 steps to do to properly install and configure log4Net NuGet package.
One of the most important steps to do is to add log4net.config file, then to add an entry to AssemblyInfo.cs file... Follow the link for further details.
Good luck!

Log4Net not working in MVC web application but working in console and window application

I have created a solution which consist of class library, MVC web application and console application.
For my class library project is actually responsible to perform logging using log4net which is also included the log4net configuration in the log4net.config. Currently i am facing a problem which the logging is not working when my web application call the logging function from class library. But it's working fine when my console application. My log4net.config looks as below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\\Temp\" />
<datePattern value="'Test.log_'yyyy-MM-dd'.log'" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<appendToFile value="true" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout, log4net">
<conversionPattern value="%date [%thread] %-5level %logger [%method] - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
I have also included the line below in my class library [AssemblyInfo.cs]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
My sample class library function as below:
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Write ()
{
log.Info("Success");
}
I have set the log4net.config Copy to Output Directory to Copy always.
Sample log4net output from console application [Test.log_yyyy-MM-dd.log]:
2019-10-01 12:07:48,923 [1] INFO ClassLibrary2.Class1 [Write] - Success
But there is log file generated for MVC web application. Is there any additional step need to configure for the web application?
I would be grateful for any help with it.
Thanks.
Did you add something in your Application_Start method? (global.asax) like:
string l4net = Server.MapPath("~/log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));
Try To Add ConfigSections in your web.config. Also there's the guide especially for MVC applications.
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
Complete Guide

How to read log4Net from web.config

I am using log4net to perform daily logging.
I realize that log4net doesn't support deleting old files in this fashion.
I am trying to write my own method to accomplish this task, however I am no sure how to read the log4net settings from the web.config file.
I've tried:
var log4NetData = ConfigurationManager.GetSection("log4net");
However I get this as my results:
The type 'System.Configuration.ConfigXmlElement' exists in both 'System.Configuration.dll' and 'System.dll'
How can I read the log4net node from my web.config?
Actually Log4Net can update the same file always (this way, there is no need to delete it and create another one).
I'm using log4Net to log always the same file n times in a hour. My configurations:
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
app.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="MyFileAppender" />
</root>
<appender name="MyFileAppender" type="log4net.Appender.FileAppender">
<file value="application.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%newline" />
</layout>
</appender>
</log4net>

Log4net Configuration Issue

Had something weird start happening to me today. I have an asp.net mvc app with log4net setup and everything had been working fine. Something must have changed somewhere and now nothing is getting logged (no log file is being created).
Here's my global.asax.cx
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
}
Here's my configuration in my web.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\logs\api\ApiLog.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
For some reason the c:\logs\api\apilog.txt file never gets created. However, if I change my application_start method to this it works fine:
log4net.Config.XmlConfigurator.Configure(new FileInfo("DirectPathToMy\web.config"));
Any ideas why calling Configure() is not finding the configuration in my web.config by default?
Don't know why your approach don't work but the issue is that you need to make sure it is activated in your project.
I usually put this as an assembly level reference in my AssemblyInfo.cs under /Properties:
[assembly: log4net.Config.XmlConfigurator()]
Reference:
http://logging.apache.org/log4net/release/manual/configuration.html

Log4Net not logging (probably not initialised)

First time playing with Log4Net and I'm running into trouble. I've followed various tutorials but I've been unable to get it to log anything out. Let me show you my code and hopefully you can tell me what I'm doing wrong.
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="CurrentLog.txt"/>
<staticLogFileName value="true"/>
<appendToFile value="true"/>
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd"/>
<filter type="log4net.Filter.LevelRangeFilter">
<acceptOnMatch value="true" />
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd MMM yyy HH:mm:ss} %level %message. %newline %exception" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>
AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
Presenter.cs
At the top of the class I have this:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Then I try to use the log variable later in the class:
bool isDebugEnabled = log.IsDebugEnabled;
log.Debug("Failed to save", e);
Whenever I inspect the isDebugEnabled variable, it is false, as are all of the other isBlahEnabled if I inspect the log variable.
My suspicion is that I have not hooked up my app.config file correctly because this is the first time I have tried to use one. I created by right clicking on the project in solution explorer, adding a new item, choosing Application Configuration File and naming it app.config.
This one works for me:
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="Main" type="log4net.Appender.RollingFileAppender">
<file value="${USERPROFILE}\My Documents\MyApp\Logs\Main.log" />
<appendToFile value="false" />
<maximumFileSize value="1GB" />
<maxSizeRollBackups value="3" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} %-5level %-18logger %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Main" />
</root>
</log4net>
</configuration>
Also be sure the build action on app.config is set to None and Copy to output dir is set to "Copy if newer". You can set these settings in the file properties.
Program.cs
public static ILog Log;
static void Main(string[] args)
{
// Setup Logging
log4net.Config.XmlConfigurator.Configure();
Log = LogManager.GetLogger("MyAwesomeApp");
// ...
}
Just to add my 2 cents: I had the same Problem, but I use the above config in separate log4net.config (so I have on all apps the same config), but I simply forgot to set the file property on build 'Copy when newer' (or similar wording, have German Version).
Just to add my 2p in case this helps anyone else searching for a resolution to this problem:
In my case I was using the NServicebus.Logging package in addition to Log4net, and this package contains types with the exact same names as those in Log4net, differing only in the namespace.
Fixing the 'using' statements or fully-qualifying the type names resolved it, but it was very hard to spot the problem.

Categories