Log4net - Does not create a log file - c#

I'm using log4net in order to create a log, but it doesn't do anything.
Here is the app.config:
<?xml version="1.0" encoding="utf-8">
<configuration>
<configSection>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSection>
<log4net>
<appender name="WriteToFile" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<layout ="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WriteToFile"/>
</root>
</log4net>
</configuration>
I have the following line in AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigur(ConfigFile ="App.config", Watch= true)]
Here is an attempt to write to the file:
private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void write()
{
log.Info("Some text here");
}
And the following line:
log4net.Config.XmlConfigurator.Configure();

If this is an executable I suppose that your config file is not called App.config at the resulting bin folder but rather MyApp.exe.config. So you may try fixing this:
ConfigFile ="App.config"
You can also skip the config file name if you are using the default:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Also make sure that the account you are running your application under has write permission to the folder in which you expect the log file to be written.
UPDATE:
Step by step guide:
Create a new Console Application
Install the log4net NuGet
Use the following in your App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="WriteToFile" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<layout type="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WriteToFile" />
</root>
</log4net>
</configuration>
And in your Program.cs:
using log4net;
using System.Reflection;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ConsoleApplication1
{
class Program
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
log.Info("Some text here");
}
}
}

I have only been successful with log4net when I ran the static Configure method:
log4net.Config.XmlConfigurator.Configure();
Wrapping it in one method below read default config for the application, be it web.config or app.config:
private static void InitLogging()
{
log4net.Config.XmlConfigurator.Configure();
_logger = Common.Logging.LogManager.GetLogger(typeof(Program));
_logger.Debug("Logging initialized");
}
It seems more elegant with an decorator attribute the way you are suggesting, but the above mentioned may be worth a try.

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!

unable to get log4net to write to file

I've been trying to pull the debug logs and for whatever reason, I can't seem to get log4net working in my web app:
My Web.config looks like:
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<section name ="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" requirePermission="false" />
</configSections>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value ="%message" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender" >
<file value ="C:\logs\testlog.txt" />
<lockingModel type ="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value ="%message" />
</layout>
</appender>
<root>
<level value ="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
in my Service.asmx.cs:
public class Service : System.Web.Services.WebService
{
public static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Service));
protected void Page_Load(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
My AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Control.ascx.cs:
protected void Page_Load(object sender, EventArgs e)
{
//NOTE: This method will be invoked whenever ANY widget on the dashboard does a postback
log4net.Config.XmlConfigurator.Configure();
}
I have given everyone permissions to the log folder.
The other item I wanted to note is that I can get this exact code to work with a standard console app without any issues. However, when I try to use it on my web app, I do not have any luck. I also wanted to say that this is a web app widget that is part of a bigger application.
One of your problems can be that you have the following in the page load:
protected void Page_Load(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
Remove this because you already have a assembly attribute that does this. The loggers you are using are static variables on the classes. They should be initialized after you call configure. In this case you call it before configure (which is in Page_Load).

Log4Net error : "Failed to find configuration section log4net"

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

Using log4net as a class library?

I'm working with a console application with c#, visual studio 2008, .net framework 3.5, windows 7. I've created a log4net library and plan to use it on several projects on my solution.
This is how my log4net library class looks like:
public class LibraryLogClass1
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Method3(string message)
{
log.Debug(message);
}
}
In my main console project I have this:
class Program
{
static void Main(string[] args)
{
LibraryLog3.LibraryLogClass1.Method3("test3");
}
}
I've added this line in my AssemblyInfo.cs in my console project:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
This is my App.config in my console project:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="C:\test3.txt"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
</log4net>
</configuration>
When I ran the program the file is not created.
How can I solve this?
thanks
If you look at the log4net documentation for assembly attributes it says this:
"Therefore if you use configuration attributes you must invoke log4net
to allow it to read the attributes. A simple call to LogManager.GetLogger will cause the attributes on the calling assembly
to be read and processed. Therefore it is imperative to make a logging call as early as possible during the application start-up, and
certainly before any external assemblies have been loaded and invoked."
In your case, your call to Method3 is loading the library assembly, so the static field is attempting to load attributes from the library log class, where the attributes aren't defined.
I generally have something like this at the start of my main program:
LogManager.GetLogger("Initialise log4net from the current assembly attributes");

Configuring/Installing log4net for RavenDB in Visual Studio 2010

I'm trying to configure my C# project to use log4net for RavenDB. I already have log4net working with a FileAppender, but the RavenAppender doesn't seem to be working right now. The following are the steps I have taken so far:
Step 1: Installing log4net.Raven
I installed the log4net.Raven library using the following NuGet Package Manager console instructions (taken from the package website linked to above):
Install-Package log4net.Raven
That command added the log4net.Raven library to my project references.
Step 2: Configuring Web.config
In my Web.config file, I have the following settings, most of which are copy and pasted from the README file for the log4net.Raven project on GitHub (the owner of log4net.Raven also has similar configuration settings published on his blog):
<!-- Example connection string config from blog -->
<configsections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net">
</configsections>
<connectionstrings>
<add connectionstring="Url=http://raven; DefaultDatabase=Log" name="RavenLogs">
<add connectionstring="Url=http://localhost:8080;user=asa;password=asa" name="SecureRaven">
</add>
</add>
</connectionstrings>
<!-- My current config -->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<connectionStrings>
<add name="RavenDB" connectionString="Url=http://localhost:8080;Database=MyDatabase" />
</connectionStrings>
<!-- Example log4net config from README.
My project uses these settings except for the connectionString value,
which is set to "RavenDB" to match the setting name above.
-->
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<!-- LogFileAppender settings here -->
</appender>
<appender name="RavenAppender" type="log4net.Raven.RavenAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<connectionString value="RavenDB"/>
<maxNumberOfRequestsPerSession value="100"/>
<bufferSize value="50" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR" />
</evaluator>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="LogFileAppender" />
<appender-ref ref="RavenAppender" />
</root>
</log4net>
Step 3: Logging from C# code
In my C# code, I have the following:
public class FooController : Controller
{
private static ILog _log = LogManager.GetLogger(typeof(FooController));
public ActionResult Index()
{
_log.Info("Hello World!");
return View("Index");
}
}
That code will write out to a log file on my workstation, so from that I know that log4net in general is working correctly. But for RavenDB, I've been checking the Documents and Logs for MyDatabase through the Raven studio in a web browser, and I do not see any Info level log with the message "Hello World".
Does anyone have any ideas of what the problem could be and how to fix it?
May be the problem is here:
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
if you don't have class named FileAppender in your project you need to add the library name where FileAppender is, for example:
<appender name="LogFileAppender"
type="log4net.Appender.FileAppender, log4net.Raven">
(the syntax for type is =" Fully qualified class name , assembly file name , version , culture , public key token ")
Try debug log4net as here Log4Net Troubleshooting
If you find this line:
log4net: Adding appender named [RavenAppender] to logger [root].
RavenAppender is working

Categories