Thursday, July 18, 2013

Using the log4net.dll isn't too tough.

using System;
namespace Whatever
{
   public class Calculator
   {
      public string Calculate(string ying, string yang)
      {
         decimal Ying = Convert.ToDecimal(ying);
         decimal Yang = Convert.ToDecimal(yang);
         decimal calulation = Ying + Yang;
         return calulation.ToString();
      }
   }
}

 
 

...may be made a bit safer like so:

using System;
using System.IO;
using log4net;
using log4net.Config;
namespace Whatever
{
   public class Calculator
   {
      public string Calculate(string ying, string yang)
      {
         var f = new FileInfo(Directory.GetCurrentDirectory() + "\\log4net.config");
         XmlConfigurator.Configure(f);
         ILog log = LogManager.GetLogger(typeof(Calculator));
         decimal Ying = 0m;
         decimal Yang = 0m;
         try
         {
            Ying = Convert.ToDecimal(ying);
            Yang = Convert.ToDecimal(yang);
         }
         catch (Exception ex)
         {
            log.Fatal(ex);
         }
         decimal calulation = Ying + Yang;
         return calulation.ToString();
      }
   }
}

 
 

Clearly log4net.config is important and we will go fishing for it in bin/Debug or bin/Release so it will need, in a Visual Studio project, a Build Action of "Content" and Copy To Output Directory setting of "Copy always" or at least "Copy if newer" to make it findable/readable. The config file looks like this:

<log4net>
   <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <file value="error.log" />
      <appendToFile value="true" />
      <maximumFileSize value="100KB" />
      <maxSizeRollBackups value="2" />      
      <layout type="log4net.Layout.PatternLayout">
         <conversionPattern value="%d{HH:mm:ss} %-5p %c - %message
               %property{adapterName}%newline" />
      </layout>
   </appender>   
   <root>
      <level value="FATAL" />
      <appender-ref ref="RollingFile" />
   </root>
</log4net>

 
 

error.log also gets written to bin/Debug or bin/Release. An entry looks like so:

14:38:13 FATAL Whatever.Calculator - System.FormatException: Input string was not in a
      correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&
         number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseDecimal(String value, NumberStyles options,
         NumberFormatInfo numfmt)
   at System.Convert.ToDecimal(String value)
   at Whatever.Calculator.Calculate(String ying, String yang) in
         c:\apps\log4net\Whatever\Whatever\Calculator.cs:line 23 (null)

No comments:

Post a Comment