unable to get log4net to write to file - c#

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).

Related

When do I need to specify log4net.Appender.FileAppender.LockingModel in ASMX services

We have a project which consists of 3 different ASMX service files for example Service1.asmx, Service2.asmx, and Service3.asmx all of which are running from the same application pool.
We've just started using log4net to log our requests and responses, and it seems to be logging every request and response for each service correctly in the same log file (which is what we want).
However, on reading log4net config examples, I've seen some examples that are using log4net.Appender.FileAppender.LockingModel.
Do I need to consider this in my scenario? This is my current code:
public class Global : System.Web.HttpApplication
{
public static readonly log4net.ILog asmxDebugLog = log4net.LogManager.GetLogger("AsmxDebugLogFile");
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
}
In my web.config file I have
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="true">
<appender name="AsmxDebugLogFile" type="log4net.Appender.RollingFileAppender">
<file value="App_Data/log4net_ASMX.DEBUG_" type="log4net.Util.PatternString" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<maximumFileSize value="5GB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<logger name="AsmxDebugLogFile">
<level value="DEBUG" />
<appender-ref ref="AsmxDebugLogFile" />
</logger>
</log4net>
</configuration>
We are logging like this
asmxDebugLog.Debug("Log something useful");
You only really need to care about locking when the loggers are not all in one process, which for you it seems they are (1 app pool ~= 1 process).
The default locking mode is 'exclusive', which is fastest, so you don't need to (or want to) change that (and slow it down).
If you later split the services into different app pools, you can then choose either InterProcess (if all on the same machine) or Minimal.

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

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

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

Categories