Log4Net Minimal Usage

Log4net - minimal info to start.

Step 1


  • Create a project using Visual Studio (the code is in c#).

Step 2


Step 3


  • Create folder lib under the project and place files there.
  • Add reference to lib\log4net.dll

Step 4


  • In the root of the project folder create XML file: log4net.config
  • In Properties for the file set: Copy to Output Directory: Copy if newer
  • Populate file with following
    • log file appender will create a file in logs folder with the file name of output.log;
    • once file size reaches 10MB, new file will be created
    • Maximum of 10 log files will beretained

Sample of log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net xmlns="urn:log4net">
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="file" value="logs\output.log" />
    <param name="appendToFile" value="true" />
    <param name="rollingStyle" value="size" />
    <param name="maxSizeRollBackups" value="10"/>
    <param name="maximumFileSize" value="10MB" />
    <param name="staticLogFileName" value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="conversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="LogFileAppender"/>
  </root>
</log4net>

Step 5


  • Under the “Properties” of the project in Solution Explorer open up AssemblyInfo.cs
  • Add the following line at the end (ConfigFile points to the configuration file, Watch flag can be set to True to apply updates to the configuration file without restarting the program):
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Step 6


  • In the file (eq: MyClass) where you want to use log functionality add the following (you can use any string you wish instead of typeof (MyClass). This, however, will indicate which project file was logging):
using log4net;

... class MyClass ...
{
  private readonly ILog Log = LogManager.GetLogger(typeof (MyClass));
  ...
}

Step 7


USAGE:

Log.Debug("This is a debug message");
Log.Info("This is an informational message");
Log.Warn("This is a warning message");
Log.Error("This is an error message");
Log.Fatal("This is a fatal error message");

Additional Comments


  • The log file can be placed anywhere in the filesystem by specifying the path in the log4net.config.
  • Make sure that running user has a CREATE and WRITE permission to logs folder (by default created in the app folder).
  • You can use NUGET to search for log4net. This will take care of steps 2 and 3.

Examples

More Info: http://logging.apache.org/log4net/