Log4net Not Creating Log File

Today in this article, we will cover below aspects,

Issue Description

If you are getting an error on a program with log4net configured, but no log file is being created then you can try below few steps to resolve the issue

Resolution

  • If you are using the .NET Core framework for your application, please make sure you are enabling the log4net using Host(ASP.NET Core) or non-host way (Console or Widows, WPF) application.

Example:

ASP.NET Core

public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.UseStartup<Startup>();
               }).ConfigureLogging(builder =>
               {
                   builder.SetMinimumLevel(LogLevel.Trace);
                   builder.AddLog4Net("log4net.config");
               });

Please match your log4net.config file with below sample config,

<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="TheCodeBuzz.log" />
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="TRACE" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

  • If you are using dynamic dates in the application for log files then please make sure to use the datePattern along with staticLogFileName in the combinations.
<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="logs\\TheCodeBuzz-" />
    <datePattern value="yyyy-MM-dd'.log'"/>
    <appendToFile value="true" />
    <staticLogFileName value="false"/>
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="TRACE" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

  • log4net config file should be available in the same location where your project deployable DLL or EXE exists. Generally, developers can use “Copy Always” setting in the project.
  • Check for forward or backsword(// or \\ ) slashes are used properly

References:

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *