Where is the log file in log4net? - asp.net-mvc

I've got the following entries in my Web.config file in an asp.net mvc application:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
...
</configSections>
<log4net>
<appender name="PublicAccessAppender" type="log4net.Appender.RollingFileAppender">
<datePattern value="'C:\Users\my_user_name\Documents\Temp\logs\public-access.'yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="PublicAccessAppender" />
</root>
</log4net>
...
</configuration>
I hope it's pretty self-explanatory what I'm trying to achieve, but when I run the application (hosted in IIS), I get no log file. FWIW, the directory hierarchy exists up to Temp folder, and I'd like log4net to generate the rest of the directories/files in the path.
I've added the log4net nuget package to my application, and I'm logging with the INFO level.
What am I missing here?

I think you can't put full path into datePattern, there must be just YYYYmmdd and things like that. Put the file path into file element:
<file value="C:\Users\my_user_name\Documents\Temp\logs\public-access.log" />
<datePattern value="yyyyMMdd" />
<preserveLogFileNameExtension value="true" />
The last element forces to put datePattern before the .log extension which was probably your original goal..

Here's the working appender configuration:
<appender name="PublicAccessAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\temp\my_user_name\Documents\Temp\logs\app.log" />
<datePattern value=".yyyy-MM-dd" /><!-- can be omitted as it's the default datePattern value -->
<rollingStyle value="Date" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
Note to readers struggling with log4net configuration: asp.net hosted in IIS pretty much has 0 write permssions, so the issue you're most likely struggling with is that your web app simply doesn't have permission to write to the log file.
That's what was happening for me, and I noticed it by inspecting the contents of log4net.LogManager.GetRepository().ConfigurationMessages in the debugger after calling .Configure().
I followed this post to give my web app the necessary persmissions to write to the log file (namely Read/Write/Modify).

Related

Log4Net not logging in .NET WebApi project using UnityContainer

I have a very basic C# .NET WebApi project using Unity.AspNet.WebApi and Unity.Mvc for dependency injection and Unity.log4net for logging.
The injection into my controllers seems to be working correctly. The problem is that the logger never logs anything. The expected .log file is never created. When I inspect the logger object while debugging it has all the levels disabled (IsDebugEnable = false, IsErrorEnabled = false, etc.)
It is running as if has ignored my log4net.config file. In the root of my project I have a log4net.config file that defines a console and a file appender.
<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="DemoWebApiUnityLog4Net.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
I have added this line to AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = #"log4net.config", Watch = true)]
The log4net was registered in to the Unity container in UnityConfig.cs with this line:
container.AddNewExtension<Log4NetExtension>();
The full demo project can be found here: https://github.com/CarmonColvin/DemoWebApiUnityLog4Net
Nothing I have tried has resulted in a successful log. Any help is appreciated.
According to the log4net FAQ:
If you are configuring log4net by specifying assembly level attributes on your assembly then the configuration will be loaded once the first call to the LogManager.GetLogger is made. It is necessary that the first call to LogManager.GetLogger made during the process (or AppDomain) is made from the assembly that has the configuration attributes. Log4net will look only once and only on the first calling assembly for the configuration attributes.
So it sounds to me like you should be calling LogManager.GetLogger() in Global.asax when the application starts in order to load your configuration. Something like:
using log4net;
protected void Application_Start(object sender, EventArgs e)
{
var logger = LogManager.GetLogger(typeof(Global));
logger.Info("Application started.");
}

Impossible (so far) to get any asp.net mvc error info on UAT IIS server

We have a web app that is running fine on dev machines and dev servers. For some very unknown reason (that's the whole point), the app does not run on our OAT server. Our situation is:
CustomErrors=Off not working
No log files
No Event Viewer entries
By design, the application is not logging anything (sad, I know). It does have a custom error redirect, which is working, but pointing to a page and controller that does not exists, it was never implemented.
So my first try was to set up CustomErrors and check on browser itself what is wrong. No luck. I have tried to change web.config:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Again, no luck. Our L2 support does not have access to modify machine.config and set , so customerror is not an option.
Next, I have tried trace and log4net files (worked on dev machine and servers):
<log4net debug="true">
<root>
<level value="ALL" />
<appender-ref ref="dasAppender" />
</root>
<appender name="dasAppender" type="log4net.Appender.RollingFileAppender">
<file value="${ALLUSERSPROFILE}\DAS\Das.webApp.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</appender>
</log4net>
Used %ALLUSERSPROFILE%, %temp%, IIS log folder. None have worked.
I don't know what to do next. Does anyone have any Idea?
Thank you
I did not solve it, but the team did.
They have added the following on web.config
<trust level="Full" />
</system.web>
and
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

Asp.net MVC log4net with lockingModel makes session lost

I get a MVC website and with the log4net to record the log.
In the web application, I store the user information in session, add log some information after executing one operation. Then the session lost when I returned to the home page(just type the url of the home page).
I am sure that the session lost which has no relation to the "Response.Redirect()" or something else, because I test the application and found it will recover after I comment the lockingModel property which value is "log4net.Appender.FileAppender+MinimalLock" in log4net config file.
Below is the configuration:
<?xml version="1.0"?>
<log4net debug="true">
<appender name="AllInfoRollingAppender" type="log4net.Appender.RollingFileAppender">
<file value="bin\\Log\\AllInfo-UniqueBlog-" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true" />
<staticLogFileName value="false" />
<rollingStyle value="Composite" />
<datePattern value="yyyy-MM-dd.LOG" />
<maximumFileSize value="1M" />
<maxSizeRollBackups value="4" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger: %message%newline%exception" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AllInfoRollingAppender" />
</root>
</log4net>
So I think the "lockingModel" property in log4net config cause this error, but i don't know the reason, and it will not throw any error there, does anyone encounter this? I found it is inconceivable because this shouldn't cause this issue.
Your question is totally not readable. However I have to things you can check. If your session is lost, do you log before or after the Session.Redirec(). If you log after the session redirect, your code is never hit. The redirect ends your current thread. Next thing you can enable log4net debugging:
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
...
</configuration>
If something bad happens in log4net, you will see it in the logs.

How to set LogLevel to error in log4net for hangfire

We have a web application and we are using log4net for logging. Recently I installed hangfire and now my log table (sqlserver db) is full of log enteries from hangfire. I want to minimise this to error and exceptions only. I believe I can set it by setting LogLevel to error but where exactly I need to do that.
Thanks
Add this logger to your web.config (log4net section)
<logger additivity="false" name="Hangfire">
<level value="ERROR" />
<appender-ref ref="HangfireLoggerAppender" />
</logger>
Adding to what #Martino mentioned above here is the exact location to add that tag in log4net section:
<log4net debug="true">
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file type="log4net.Util.PatternString" value="%property{LogFileName}" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<logger additivity="false" name="Hangfire">
<level value="ERROR" />
<appender-ref ref="HangfireLoggerAppender" />
</logger>
</log4net>

How to enable Common.Logging.Log4Net

I am trying to enable Common.Logging.Log4Net to write all types of logs to a log file. The tutorials make it look so simple but I don't know what I am doing wrong. These are the steps I am taking:
Create a new ASP.NET MVC empty project
Install the "Common Logging Log4Net 1211" NuGet package
Add the following lines to the default web.config:
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
<appender name="FileAppender" type="log4net.Appender.FileAppender" >
<param name="File" value="C:\Users\MyName\Downloads\log.txt" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
Make sure the app. pool identity account has RW access to the path where I am trying to save the log file.
Throw a random exception from code for testing purposes.
Am I missing anything? Is there a way I can debug log4net? Please help this poor soul. Thank you.
The issue was related to the NuGet package for "Common.Logging.Log4Net" changing the name of the assembly. This actually fixed it (plesae note the new assembly name, being Common.Logging.Log4Net1211):
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net1211">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
https://stackoverflow.com/a/756241/3469201
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
Then, to determine the file in which you want to save the output you can add the following code in the same .config file:
<configuration>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
...
</configuration>
I'm not familiar with Common.Logging.Log4Net. Here is the simple log4net steps that I use -
Install log4net from NuGet.
Insert the following settings in web.config (you can configure the way you want)
Then log.
If you want to use IoC container, you can read my question I asked last month.
web.config
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</root>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
Testing inside Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
XmlConfigurator.Configure();
// You can inject it to your code using IoC container.
var logger = LogManager.GetLogger(typeof(MvcApplication));
logger.Debug("Test Debug.");
logger.Error("Test Error.");
logger.Fatal("Test Fatal.");
logger.Info("Test Info.");
}
}
Result
2015-06-04 11:48:05,885 [1] DEBUG DemoLog4Net.MvcApplication [(null)] - Test Debug.
2015-06-04 11:48:05,921 [1] ERROR DemoLog4Net.MvcApplication [(null)] - Test Error.
2015-06-04 11:48:05,922 [1] FATAL DemoLog4Net.MvcApplication [(null)] - Test Fatal.
2015-06-04 11:48:05,922 [1] INFO DemoLog4Net.MvcApplication [(null)] - Test Info.

Resources