128

Hey I have this configuration in my web.config

<log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
        <param name="File" value="mylog.log" />
        <param name="AppendToFile" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="" />
            <param name="Footer" value="" />
            <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Header]\r\n" />
            <param name="Footer" value="[Footer]\r\n" />
            <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="LogFileAppender" />
        <appender-ref ref="ConsoleAppender" />
    </root>
</log4net>

but log4net is not working. My project compiles fine, and I get no errors debugging either. The lines where I tell to log.debug("somemessage") gets run fine, but I can't find the mylog.log file, so where is it?

1

18 Answers 18

316

One gotcha for this type of thing is to make sure to add the XmlConfigurator attribute to the assembly by placing the following line in your AssemblyInfo.cs:

[assembly: log4net.Config.XmlConfigurator]

Otherwise log4net never activates.

5
  • 5
    This method used to work in my project, but it stopped working somehow. I had to use this method stackoverflow.com/a/1479343/193634 to make it work again. Commented Apr 24, 2013 at 10:32
  • I just tried it again and it works fine. Most likely you are not referencing/loading the assembly that contains the AssemblyInfo as soon as you thought.
    – Kirk Woll
    Commented Apr 24, 2013 at 14:08
  • For those using ELMAH appender this is the way to go. I had 'log4net.Config.XmlConfigurator.Configure();' in global.asax.cs and it was working fine for file appender but not for ELMAH appenders. Commented Nov 25, 2015 at 19:44
  • 1
    I've up-ticked this answer and found I needed to tweak it with ` [assembly: log4net.Config.XmlConfigurator(Watch = true)] ` Commented May 28, 2019 at 7:09
  • or [assembly: XmlConfigurator(ConfigFile = "log4net.config")], if log4net configured in separate file, '/log4net.config', as in my case
    – dtwk2
    Commented Nov 17, 2021 at 15:20
51

I guess that either log4net is not logging at all, or the file is not ending up where you expect it.

Firstly, have you actually called

XmlConfigurator.Configure()

anywhere in your code? If the xml snippet above is in the application configuration file, this call will do the trick. If the xml snippet is in it's own file, you'll need to use the .Configure(string) overload that takes the path to the file. Without this call (or apparently the assembly level attribute mentioned by Kirk Woll), then log4net won't be logging at all.

If you believe this is all done, and log4net should be logging, then maybe you should put a fully qualified path in for the log file while you debug further. That will let you be sure where the file should be.

0
35

There is another small gotcha, see here: http://logging.apache.org/log4net/release/manual/configuration.html#dot-config

the [assembly: log4net.Config.XmlConfigurator] method doesn't work with app.config. If you configure log4net from app.config, you must use the log4net.Config.XmlConfigurator.Configure() method.

2
  • Just for the record, both methods worked for me in an console application.
    – rageit
    Commented Jul 18, 2016 at 20:09
  • I confirm the solution above - I had to invoke log4net.Config.XmlConfigurator.Configure(); in my code (which uses app.config to have log4net effectively work. Lines which get effectively printed are those subsequent to the execution of Configure() method.
    – luisa rosi
    Commented Mar 23, 2020 at 20:10
23

Here is my checklist for when log4net is proving to be recalcitrant:

  • ensure that log4net.config file is copied to the bin\ folder when building (set to 'Copy if newer' in compiler)
    • when dealing with installed code, ensure that the log4net.config came along for the ride (set to 'Content' in compiler)
  • ensure that the user that the process runs as has write rights to the folder where the logs are to be written
  • if in doubt, give promiscuous permissions to c:\temp\ and get everything to log to there ()
  • fire up Sysinternal/Dbgview.exe to see if that tells you anything
1
  • 4
    "ensure that log4net.config file is copied to the bin\ folder when building (set to 'Copy if newer' in compiler)" -> save my day! Thks so much! Commented Sep 29, 2014 at 9:18
9

For an ASP.NET MVC project adding

log4net.Config.XmlConfigurator.Configure();

to the Global.asax.cs also helps:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        log4net.Config.XmlConfigurator.Configure();
    }
}
5
  • 1
    Had a very weird issue with this, in production and on my boss's computer the loggers worked fine like this, but not until I Kirk's answer did it work on my computer. Just thought I'd let people know in case they have similar issues (MVC project btw).
    – Shelby115
    Commented Jul 30, 2015 at 14:22
  • @Shelby115, many many thanks! I was trying to put my log4Net entries in ELMAH. I had everything correct in web.config. I already had 'log4net.Config.XmlConfigurator.Configure();' in my global.asax.cs but it wan't working. Came to this SO post and added the line to assemblyInfo.cs based on Kirk's. It still didn't work!. After reading your comment I deleted the previous entry from global.asax.cs and it started working. I spent several hours on this and your comment was a big help. Thanks again! Commented Nov 25, 2015 at 19:38
  • The entry in global.asax.cs was working fine for file appender but not for ELMAH appenders. Kirk's way worked for ELMAH appender (I specifically had to remove it form global.asax.cs) Commented Nov 25, 2015 at 19:42
  • You might also want to ensure that log4net has write permissions to the directory configured for the log files. Commented Nov 26, 2015 at 11:12
  • @Shelby115 Dang, gotta love it when you forget the solution and your own comment solves your problem. Coming to a page with an answer already upvoted by you is a good indicator too.
    – Shelby115
    Commented Apr 5, 2017 at 14:57
7

These are the steps which eventually got my file logging working:

  • -Check AssemblyInfo.cs contains the following attribute. [assembly: log4net.Config.XmlConfigurator]. This loads log4net.
  • Check the log directory has write permissions.
  • Check the logger has a format specified. This is done by checking each element in your configuration has a layout element specified. Eg:

<appender name="MainLogger"... <layout type="log4net.Layout.SimpleLayout"/>

  • Finally, try turning on log4net internal logging to enable console logging and checking the console. To do this, add <add key="log4net.Internal.Debug" value="true"/> to your appSettings.
2
  • <add key="log4net.Internal.Debug" value="true"/> This helped me to troubleshoot the issue. Thanks Commented Oct 13, 2016 at 17:29
  • The directory's permissions is what got me Commented Oct 4, 2018 at 17:20
6

I've had experiences where logging systems fail silently without raising exceptions. I suppose this makes sense because if the logger is logging errors then how can it log an error that it's unable to perform logging?

So if the file isn't created on disk, start by looking into file system permissions to ensure the user your application is running under can write a new file to that disk location.

For testing purposes you might want to manually create the file on disk that should be written to and open up permissions for everybody to write to it. If the logger starts writing to it then you know it's permission based rather than configuration based.

5

On my side, I forgot to mark the config file to be copied while the app is being compiled.

Copy the config file to output directory

Just right click the log4net.config file, select property and then choose Copy to Output Directory to be Copy XXXX

2

Unfortunately none of the above helped. Explicit configuration in the class to be logged additionaly to the previous settings suggestions did the trick for me.

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
log4net.Config.XmlConfigurator.Configure(new FileInfo(assemblyFolder + "/log4net.config"));
1
  • Thanks none of the above worked but yours. You are my hero!
    – Patrick
    Commented May 10, 2021 at 11:19
2

So, in the Accepted Answer, the solution was to put

[assembly: log4net.Config.XmlConfigurator]

into the AssemblyInfo.cs File.

Also, there was a comment sugesting

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

however, if it is still not working, consider configuring the name of your log4net config file (log4net.config in my case):

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

after that, logging worked like a charm.

1

I tried all of the above but nothing worked. Adding this line in app.config's configSections section worked for me.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />

Ensure that Version and PublicKeyToken is correct

0
<param name="File" value="mylog.log" />

is saying "write mylog.log to actual folder". This means that if your webapp is under IIS, then log will be written to C:\inetpub\wwwroot\appname\mylog.log.

If log file is not there, then maybe account under which is app running doesn't have write permission on folder. You can run Process Monitor from SysInternals to see if and where a file is written.

Also run VS in debug mode, to see if any exceptions are thrown (Debug->Exceptions->CLR Exceptions, check Thrown).

0

In my case I forget to set the log4Net.config file properties as "Content" so the file was not included in the deploy. So pay attention on it:

Compile action : Content
0

Check your Reporting level is set to "Debug" or "ALL". This caught me and I spent ages trying to debug my log4net setup. I had it set to Error and as it wasn't erroring it didn't log anything.

0

Aside from all the other answers, my problem that was I needed a call to GetLogger() in my start-up class (WinForms example):

static class Program
{
    public static readonly ILog MainLog = LogManager.GetLogger("Main");

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

All my 'meaningful' logging statements were in a DLL that is apparently loaded too late for log4net.

0

We also had problems with log4net not working and in our case the problem was that the config file had Windows line breaks instead of Unix line breaks.

0

I faced a similar situation, I was not getting my txt file in any of the directory. One important catch is to add and register your logger in web.config.

<appender name="YourErrorLogger" type="log4net.Appender.RollingFileAppender">
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <file value="Error_Logs\" />
  <staticLogFileName value="false" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

After Adding your appender then provide its name and reference like this in logger tag:

<logger additivity="false" name="ErrorLogger">
  <level value="All" />
  <appender-ref ref="ErrorLogger" />
</logger>

I tried all the above techniques but the one thing that I was missing was this.

-7

Also after some hours, I figured out why it wasn't working for me...

i had:

public static class Program
{

    private static CommunicationManager _bcScanner = new CommunicationManager();
    private static ILog _log = LogManager.GetLogger(typeof(Program));
    private static SocketServer socketListener;

but it should be:

public static class Program
    {
        private static ILog _log = LogManager.GetLogger(typeof(Program));
        private static CommunicationManager _bcScanner = new CommunicationManager();
        private static SocketServer socketListener;

So make sure the ILog is on the first line....

1
  • 1
    This is definitely not the cause. It doesn't matter when you initialize the ILog object as long as you do that before you make a call to the logging methods i.e _log.Info; _log.error etc. Commented Jun 24, 2015 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.