简体   繁体   中英

Appending to File using log4net in C#

I'm new to log4net and would like to create a simple console application that does the following:

  1. Reads a number as an input

  2. Loops that many iterations

  3. Prints the time it took to run the loop
  4. Creates a log file in the following format :

MM/DD/YYYY - Input: <num> - Time: <time> ms

In my AssemblyInfo.cs I added the following line:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

My App.config looks like this:

<?xml version="1.0" encoding="utf-8" ?>                       
   <configuration>                                           
       <configSections>
            <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> 
       </configSections>                                            
       <log4net>                                                    
           <appender name="FileAppender" type="log4net.Appender.FileAppender">
               <file value="MyLog.txt" />
               <appendToFile value="true" />
               <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
               <layout type="log4net.Layout.PatternLayout">
                   <conversionPattern value="%dateExtra Info: %property{input}%property{time}%newline" />
              </layout>
              <filter type="log4net.Filter.LevelRangeFilter">
                  <levelMin value="INFO" />
                  <levelMax value="FATAL" />
             </filter>
         </appender>                                                   
         <root>
             <level value="INFO"/>
             <appender-ref ref="FileAppender"/>
         </root>                                                    
      </log4net>                                                                          
      <startup>
          <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />                                  
    </startup>                                               
  </configuration>

My code looks like this:

using log4net;
using System;
using System.Diagnostics;
namespace ConsoleApplication1
    {
        class Program
        {
            private static long num;
            private static readonly ILog log = LogManager.GetLogger
                (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            static void Main(string[] args)
            {
                Console.Write("Please enter a number: ");
                try
                {    
                    // gets number as input
                    num = long.Parse(Console.ReadLine());
                    if (num <= 0) throw new Exception("Number must be positive and non zero");
                }
                catch (FormatException e)
                {
                    Console.WriteLine(e.Message);
                    Console.Read();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.Read();
                }
                // create new stopwatch instance
                Stopwatch sw = new Stopwatch();
                // starts the timer
                sw.Start();
                // runs loop [num] times
                for (long i = 0; i < num; i++) ;
                // stops the timer
                sw.Stop();
                Console.WriteLine("Loop ran for {0}ms", sw.ElapsedMilliseconds);
                GlobalContext.Properties["input"] = " - Input : " + num;
                GlobalContext.Properties["time"] = " - Time : " + sw.ElapsedMilliseconds + "ms";
                Console.Read();
            }
        }
    }

The file does get created but it is created empty. What could be the problem here?

You need to log something with commands like

log.Info(string.Format("Input: {0} - Time: {1}ms", input, time)); 

That is something like

using log4net;
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
    class Program
    {
        private static long num;
        private static readonly ILog log = LogManager.GetLogger
              (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            ...
            Console.WriteLine("Loop ran for {0}ms", sw.ElapsedMilliseconds);
            log.Info(string.Format("Input: {0} - Time: {1}ms", num, sw.ElapsedMilliseconds)); 
            ...
        }
    }
}

Have a look at: https://stackify.com/log4net-guide-dotnet-logging/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM