Log file creating using Log4net in Asp.net and C#

Log file creating using Log4net in Asp.net and C#

By adding log4net.dll reference to project we can create log file. I will show you step by step process below.

Step:1

Create a new project and add one web form like webform.aspx.

Step:2

Then next in the solution explorer right click on references. Click on add reference. A window is opened in that click on browse and select log4net.dll (you can get this from internet or download from above)

Step:3

Now open the Web.config from solution explorer and add below code.
<configuration>
       <configSections>
              <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"></section>
       </configSections>
      

       <log4net>
              <appender name="FileAppender" type="log4net.Appender.FileAppender">
                     <param name="File" value="E:\Lfile.txt"/> <!—log file location-->
                     <param name="AppendToFile" value="true"/>
                     <layout type="log4net.Layout.PatternLayout">
                           <param name="ConversionPattern" value="%d{yyyy-MM-dd hh:mm:ss} - %C{1}.%M-%-5p- %m%n"/>
                     </layout>
              </appender>

              <root>
                     <level value="ALL"/>
                     <appender-ref ref="FileAppender"/>
              </root>
       </log4net>

</configuration>

Step:4

Now open properties folder in solution explorer and open AssemblyInfo.cs file then add below code.
[assembly:log4net.Config.DOMConfigurator] //for starting log4net


Step:5

In webform1.aspx add below code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

Step:6

Go to webfrom1.aspx.cs add below code.
public static readonly log4net.ILog logfile = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        protected void Page_Load(object sender, EventArgs e)
        {
            const string a = "Hi";
            logfile.Info("log file test");//write only text
            logfile.InfoFormat("logfile test with other values" + a); // write text with values
            Label1.Text = "log file created";
        }

In the above code we have 2 types of log file writing.
  1.“Logfile.info” is for only given test writing.   
  2. “Logfile.infoformat” is for write text with assigned values.
Note: logfile.txt created automatically.
Now run the program and check for logfile where specified location.


Happy coding!!

1 comment: