Wednesday, March 5, 2014

Log4net for VB.net and C#

0. add dll reference
1. add YourApplicationName.exe.Log4Net file to project

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <log4net>
    <appender name="ExampleAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="E:\Data\Logs\YourApplication\YourApplication_"/>
      <param name="RollingStyle" value="Date"/>
      <param name="DatePattern" value="yyyy_MM_dd'.log'"/>
      <param name="StaticLogFileName" value="false"/>
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="3" />
      <maximumFileSize value="100KB" />
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level - [%logger] %C{1}.%M %message%newline" />
      </layout>
    </appender>
    <logger name="YourApplication">
      <level value="ALL" />
      <appender-ref ref="ExampleAppender" />
    </logger>
  </log4net>
</configuration>


2. change AssemblyInfo.vb add the line below to end of file

VB.net
<Assembly: log4net.Config.XMLConfigurator(ConfigFile:="YourApplicationName.exe.Log4Net", Watch:=True)>

C#
[assembly: log4net.Config.XmlConfigurator(ConfigFile="YourApplicationName.exe.Log4Net",Watch = true)]

3. configuration file needs to be added to setup project otherwise would not work

4. if ms access mdb access need to change project compile property to dot net framework 4 from framework 4 client

5. while debugging need to copy config file to the debug directory (this is automatically done if step 3 is done)

6. Code

VB.net

Imports log4net
Imports log4net.Config
Imports log4net.Layout

  Public m_Log As log4net.ILog
 m_Log = log4net.LogManager.GetLogger("YourApplication")
        m_Log.Info("Started...")


C#
using log4net;
using log4net.Layout;
using log4net.Config;

private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger("YourApplication");
m_log.Info("started");

7. Make sure add the YourApplicationName.exe.Log4Net to setup project. It has to be in the application folder otherwise it would not work.

8. error you may see (http://sadi02.wordpress.com/2008/06/29/log4net-tutorial-in-c-net-how-can-i-show-log-in-a-file/ has the following comments)
If you’re working with Visual Studio 2010 default setup you’ll probably get the error: The name ‘log4Net’ does not exist in the current context.
The reason is that your target framework is “.Net Framework 4 Client profile”.
Right click your project -> properties ->change target framework to “.Net Framework 4″

No comments:

Post a Comment