Saturday 3 December 2016

Log4Net - Logging in to Log text File in Asp.net Application step by step

FrameWorkUsed in this application 2.0

Step 1 : Click here to Download Log4net Dll from official site.

Step 2 : Unzip the Downloaded Zip File. Navigate to this path .
C:\Users\Gokul\Downloads\Compressed\log4net-1.2.15-bin-newkey_2\log4net-1.2.15\bin\net

Step 3 : Select your asp.net framework version folder and click on release folder ,

C:\Users\Gokul\Downloads\Compressed\log4net-1.2.15-bin-newkey_2\log4net-1.2.15\bin\net\2.0\release

and copy log4net.dll from that folder and paste it in the bin folder of your applciation.

For Ex : C:\Users\Gokul\Documents\visual studio 2010\Projects\Log4net2.0\Log4net2.0\bin

Step 4 : Now add reference of log44Net dll to your applcaition by  ,

Right Clicking on you Project , Add Reference > click on Browse  .

Navigate to the path of Bin where You pasted the Log4Net dll.
For Eg : Here C:\Users\Gokul\Documents\visual studio 2010\Projects\Log4net2.0\Log4net2.0\bin

Select the Log4net dll from that path and then click ok to the Log4net dll Reference to our Project.

Step 5 : Now in Your Assemblyinfo.cs File , add this line of code

[assembly: log4net.Config.XmlConfigurator(Watch = true)] as showed in image Below.



Step 6 :
Now add this line of Code in your Global.asax in the Application_Start

 protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();

         }

Step 7 : Now in web.config file add this code in , <configuration> Section

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

  </configSections>
<log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="D:/log.txt"/>
      <appendToFile value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="1MB"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.SimpleLayout"/>
    </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingFileAppender"/>
    </root>

  </log4net>

Like below in my Web.cofig file ,



Step 7 : In the web pages where you want to Log your Information of the user activities .
Add this Line of code , as below in image of my sample Default.aspx page.

 private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);



log.Info(" Your Message here to log when user visited this page .");