Log4net doesn't write to file - c#

I want add new log to file.this is my appender:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="mylogfile.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="5"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<filter type="log4net.Filter.StringMatchFilter">
<stringToMatch value="test"/>
</filter>
<filter type="log4net.Filter.StringMatchFilter">
<stringToMatch value="error"/>
</filter>
<filter type="log4net.Filter.DenyAllFilter"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline%exception"/>
</layout>
</appender>
<root>
<level value="All"/>
<appender-ref ref="RollingFileAppender"/>
</root>
and on my class I add
[assembly: XmlConfigurator(Watch = true)]
and I add access everyone for the file but: log4net doesn't write to file. Why?

Log4net fails silently when there's a problem. The design conceit is that no logging is preferable to taking down the application. To figure out what's wrong, turn on Log4net's internal debugging by adding this key to your [app/web].config file:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
The debug messages will be written to the console or to the System.Diagnostics.Trace system. More details from Phill Haack at http://haacked.com/archive/2006/09/26/Log4Net_Troubleshooting.aspx/
There are any number of reasons Log4net might fail. Permissions problems on the log file directory, for starters (especially true for server processes, where your likely running under a restricted set of permissions for security).

You just need to call Configure:
log4net.Config.XmlConfigurator.Configure();
You can see more details here:
Log4net does not write the log file

You need to initialise the logging as the very first step in your app, and from the same assembly that you have the [assembly] tag:
From the docs:
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.
Add something like this in your start up code:
LogManager.GetLogger("Initialises logging from assembly attributes");

You should add this config section:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
to refer the log4net configuration.

Related

Not able to get log4net working to write to file

I am using sharpdevelop to create a console application in C#. I have added in the reference for log4net and I added my logging statements while I was writing the code but I never looked at the log file. Now I am done with the code I need to get the log file working. My program runs fine, even the logging statements, but I can't find the log file.
I have tried to cobble together a couple of examples on getting log4net working. I have the lines to read from the configuration and then to instantiate the object, these are the first lines in my program to run:
log4net.Config.XmlConfigurator.Configure();
ILog datalogger = LogManager.GetLogger("myLog"); //initiate the data logger
Then in various places throughout the code I have this:
datalogger.Info(DateTime.Now.ToString() + ": using file: " + ProDirectory.ToString() + #"\" + myProFile.ToString());
I have also put the following in my app.config file:
<appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
<file value="myLog.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%n" />
</layout>
</appender>
<logger name="myLog">
<level value="All"></level>
<appender-ref ref="myLogAppender" />
</logger>
No matter what I do, I can't see the log file being produced. I have changed the directory and even paused the program to see if I could find a handle open to the log file. Each time I come up empty. Not sure what I could be doing wrong.
not sure if this will help. I also had hard times making log4net work in different scenarios.
I use log4net root xml node to specify the appender. hope it will help.
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="250KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
UPDATE
You might also want to check Visual Studio output log. First setup the output log to log "ALL" (somewhere in VS settings). Then you should see exact error message of log4net in the output window of Visual Studio.
Whenever I have had issues with log4net creating the log file, it usually wound up being a file / directory permissions issue.
Change your <file value="log.txt" /> to something that you know will be accessible by the current user / process running devhost.
For example: <file value="%USERPROFILE%\Documents\log.txt" /> will create a log file in the user's My Documents folder. This is a folder that the user has permissions to write data to, and shouldn't give you any troubles with.
For more information on special folder values, see this link.
Looks like I just had to clean up my XML a little, after I did the log file is working fine:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections> <!-- Level 1 -->
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/> <!-- Level 2 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<log4net>
<appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
<file value="myLog.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%n" />
</layout>
</appender>
<logger name="myLog">
<level value="All"></level>
<appender-ref ref="myLogAppender" />
</logger>
</log4net>
</configuration>

Log4Net Not Logging When Deployed

Using version 1.2.11. Logging works on my dev machine, but won't create the directory or log when deployed.
I tried:
giving full directory access to IUSR, Everyone, local users.
running the app pool as a local admin account.
to use internal debugging as Phil Haack describes here.
Stopped and started the app pool after each change.
Nothing is produced in the output file.
My log4Net config is below. Any thoughts on what to try next?
<?xml version="1.0"?>
<log4net debug="true">
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file value="..\Logging\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<threshold value="DEBUG" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="console" type="log4net.Appender.DebugAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="file" />
<appender-ref ref="console" />
</root>
</log4net>
If the directory and the file is not being created, then most likely, the configuration is not being read (and therefore used) at runtime.
I always forget to add the single line of code for Log4net that hooks up the configuration. This code usually appears in the bootstrap class in the application (e.g. Global.asax for an ASP.NET app).
XmlConfigurator.Configure(new System.IO.FileInfo(configFile)); // configFile being the path to the file.
Instead of the above in-line, you can add this attribute to the AssemblyInfo.cs file:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Either way, this will wire up log4net. More information is found in the Manual Configuration section of the log4net docs.
If you're using IIS, make sure the correct group has modify access to the Logs folder (usually IIS_USERS).
Sounds like a permissions issue to me. I almost always use a directory where I don't have to enable any special permissions for the applications to write the log files to.
Here is what I generally use with log4net:
<file type="log4net.Util.PatternString" value="${ALLUSERSPROFILE}/<Company Name>/Logs/<Program Name>/<Log file name>.txt" />
Of cource you'll need to substitute Company Name, Program Name and Log file name in the above with actual values.
This will write to the ProgramData folder where access is typically not restricted. You can navigate to this folder in File Explorer by typing %ProgramData% or %AllUsersProfile%
Another thing I like about this method is that it works on nearly every microsoft O/S. XP, Vista, 7, 8
You probably do not know where you are logging:
<file value="..\Logging\log.txt" />
Will is derived from your running directory, which is iis its directory. You can better use a full path like:
<file value="c:\Logging\log.txt" />
Then you can give the right access rights to the logging directory. Log4net will not create any directories as far as I know. So you have to create the c:\logging directory first.
Non of the answers worked for me until I put these lines to the web.config app settings:
<add key="log4net.Config" value="Log.config" />
<add key="log4net.Config.Watch" value="True" />

How log4net doesn't clear log each time calling XmlConfigurator.Configure() in a process

In my application, I include 3 libraries:
Log4net
Common.Logging.log4net
Quartz (use Common.Logging.log4net to write logs)
This is my log4net section config:
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="quartz.log" />
<appendToFile value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
Everything is ok but having a problem about XmlConfigurator.Configure(). This command are called 2 times by order:
Called when init application -> I write log.
Called when starting Quartz. (I verified when to read source codes Common.Logging.log4net) -> Quartz write log.
After Quartz started, my logs was cleared because of XmlConfigurator.Configure(). This means that when calling this command, log will be cleared. I don't want my log is cleared after this command called in a process.
I can get source dll Common.Logging.log4net to change code to check whether log4net is really configured yet, and calling XmlConfigurator.Configure() if not. But I don't like this solution.
Please help me to find another solution without change codes in DLL library.
More info: http://neilkilbride.blogspot.com/2008/04/configure-log4net-only-once.html
You have configured that the file appender creates a new log file when log4net is reconfigured:
<appendToFile value="false" />
Change this to:
<appendToFile value="true" />
The log messages will be appended at the end of file, even if you call XmlConfigurator.Configure() multiple times.

log4net fails to log

So for some reason our logger has stopped logging and I am at a complete loss as to why.
What I'm using in my project is the following:
The log4net configuration:
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="UdpAppender" />
<appender-ref ref="RollingFile" />
</root>
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<remoteAddress value="127.0.0.1" />
<remotePort value="8180" />
<layout type="log4net.Layout.XmlLayoutSchemaLog4j">
<locationInfo value="true" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="Logs/DA.RA.log"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<appendToFile value="true"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10MB"/>
<rollingStyle value="Size"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date %logger - %message%newline"/>
</layout>
</appender>
</log4net>
In my web.config I have the following line:
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=a3d255455d3dcb36"
requirePermission="false"/>
In my global.asax I have the following line in the application_start method:
string filename = Server.MapPath( #"~\XML\log4net.xml" );
log4net.Config.XmlConfigurator.ConfigureAndWatch( new System.IO.FileInfo( filename ) );
and when I call the logger in any of my pages I use:
private static readonly ILog logger = LogManager.GetLogger(typeof(ReportParameters));
I have tried many different things I found online. These include:
adding the following line to the assembly in my project
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
I tried:
[assembly: log4net.Config.XmlConfigurator()]
I've upgraded the version of my log4net.dll from 1.2.10.0 to 1.2.11.0.
I tried adding the log4net appenders to the web.config file instead of in it's own file, and I still get nothing out of the logging.
Try opening internal debugging of log4net and check or share the result:
Note: I made a sample app and used your same log4net.xml file and ConfigureAndWatch statement and it worked without a problem. I think you are having a filename path resolution problem or permission to write problem. Create log folder If you didn't.
You need to add to web.config
<appSettings>
<add key="log4net.Internal.Debug" value="true" />
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="c:\\inetpub\\wwwroot\\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
Other than a possible file permission issue, I have found that when using
[assembly: log4net.Config.XmlConfigurator()]
in ASP.NET projects, that it would never actually do anything (I was using the debug string appender).
The solution for me was to start up log4net within the Application_Start even in global.asax.
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
}
Replace this:
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=a3d255455d3dcb36"
requirePermission="false"/>
For this:
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"
requirePermission="false"/>
And instead of
log4net.Config.XmlConfigurator.ConfigureAndWatch()
Call
log4net.Config.XmlConfigurator.Configure();
Let me know if it works that way

Issue using .net 2.0 Logger Class

I have been trying to use the class located here . But I have not been able to get this to work. I obviously do not understand something correctly, But I am curious how to get that example Logger class to work.
My research has sent me towards using MSBuild but the use of MSBuild correctly is still baffeling me. Any pointers would be helpful. I have built the logger class into a .dll,and referenced it in the project as well, but that is where my research seemed to run dry with helpful information.
My goal currently is just to get the above noted logger class working so I can use my own logger class.
That class is specifically for logging MSBuild events. If you want a generic logger that has nothing to do with MSBuild look at some of these alternatives:
MS Enterprise Library - Logging Application Block
Log4Net
Elmah (designed for logging ASP.NET errors, but can be used to log other events)
NLog
Don't be afraid of using a library to do the work. In the tutorial here for log4net it's a simple seven step process to start using a fully functional and scalable logging library. I'm going to inline pieces of the tutorial just in case the link ever dies.
First you build a very simple configuration section in your App.config file:
<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" >
<param name="File" value="log-file.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
For your needs you pretty much just need to change the value of the first param named File as it's already setup to append to a text file.
Next you'll need to run the configuration in some startup method, like Application_Start or the main method of your program.
log4net.Config.XmlConfigurator.Configure();
Finally, just use it by plugging in a couple of lines:
private static readonly ILog log = LogManager.GetLogger(typeof(Bar));
... (rest of class)
... (somewhere in a method) ... log.Debug("this is the first log message");

Categories

Resources