[asp.net] Log4net does not write the log in the log file

I have created a simple scenario using Log4net, but it seems that my log appenders do not work because the messages are not added to the log file.

I added the following to the web.config file:

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>        
</configSections>

<log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <file value="D:\MyData\Desktop\LogFile.txt" />
            <appendToFile value="true" />
            <encoding value="utf-8" />
            <layout type="log4net.Layout.SimpleLayout" />
    </appender>


    <root>
        <level value="INFO" />
        <appender-ref ref="LogFileAppender" />
    </root>
</log4net>

Within the global ASAX file I have added:

ILog logger = LogManager.GetLogger(typeof(MvcApplication));

And within the Application_Start method:

logger.Info("Starting the application...");

Why the test log "Starting the application..." is not being added to the log file?

This question is related to asp.net asp.net-mvc logging log4net log4net-appender

The answer is


Insert:

 [assembly: log4net.Config.XmlConfigurator(Watch = true)]

at the end of AssemblyInfo.cs file


Make sure the following line code should be there in AssemblyInfo.cs file.

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

and also check for this line in Application_start() method.

log4net.Config.XmlConfigurator.Configure();

There are a few ways to use log4net. I found it is useful while I was searching for a solution. The solution is described here: https://www.hemelix.com/log4net/


As @AndreasPaulsson suggested, we need to configure it. I am doing the configuration in AssemblyInfo file. I specify the configuration file name here.

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

In my case, log4net wasn't logging properly due to having a space in my project name. Drove me nuts why the same code worked just fine in a different project, but didn't in the new one. Spaces. A simple space.

So, beware spaces in project names. I've learned my lesson.


In my case I had to give the IIS_IUSRS Read\write permission to the log file.


Also, Make sure the "Copy always" option is selected for [log4net].config

enter image description here


Use this FAQ page: Apache log4net Frequently Asked Questions

About 3/4 of the way down it tells you how to enable log4net debugging by using application tracing. This will tell you where your issue is.

The basics are:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="log4net.Internal.Debug" value="true"/>
    </appSettings>
</configuration>

And you see the trace in the standard output


For me I moved the location of the logfiles and it was only when I changed the name of the file to something else it started again.

It seems if there is a logfile with the same name already existing, nothing happens.

Afterwards I rename the old file and changed the log filename in the config back again to what it was.


Your config file seems correct. Then, you have to register your Log4net config file to application. So you can use below code:

var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

After registering process, you can call below definition to call logger:

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

log.Error("Sample log");

Make sure the process (account) that the site is running under has privileges to write to the output directory.

In IIS 7 and above this is configured on the application pool and is normally the AppPool Identity, which will not normally have permission to write to all directories.

Check your event logs (application and security) to see if any exceptions were thrown.


For me I had to move Logger to a Nuget Package. Below code need to be added in NuGet package project.

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

See https://gurunadhduvvuru.wordpress.com/2020/04/30/log4net-issues-when-moved-it-to-a-nuget-package/ for more details.


Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to logging

How to redirect docker container logs to a single file? Console logging for react? Hide strange unwanted Xcode logs Where are logs located? Retrieve last 100 lines logs Spring Boot - How to log all requests and responses with exceptions in single place? How do I get logs from all pods of a Kubernetes replication controller? Where is the Docker daemon log? How to log SQL statements in Spring Boot? How to do logging in React Native?

Examples related to log4net

How to use log4net in Asp.net core 2.0 Configure Log4Net in web application log4net hierarchy and logging levels Correct way of using log4net (logger naming) app.config for a class library Log4net does not write the log in the log file Where will log4net create this log file? Configure Log4net to write to multiple files Log4net rolling daily filename with date in the file name log4net vs. Nlog

Examples related to log4net-appender

Log4net does not write the log in the log file