Everything about Log4Net


log4net is a library to help the programmer output log statements to a variety of output targets by Apache Software Foundation (official page = http://logging.apache.org/log4net/).You can also download either source code or compiled library.

It is compatible for .net project(s) and need to know couple basic things to use in your project easily.

First of all, There is a configuration you have to set before adding into your project.

Here is a sample about inserting log into a given file.

app.config file;
   <!--Start Code-->
      <?xml version="1.0" encoding="utf-8" ?>
         <configuration>
            <configSections>
                  <section name="log4net"
                  type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>   
            </configSections>
         <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
         </startup>
         <log4net>
            <appender name="FileAppender" type="log4net.Appender.FileAppender">
               <file value="log.txt" />
               <appendToFile value="true" />
               <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
               <layout type="log4net.Layout.PatternLayout">
                  <conversionPattern value="%date [%thread] %level %logger : %message %newline %date        
                        [%thread] %level %logger : %exception{message} - %exception{source} -
                        %exception{stacktrace} - %exception{targetsite} - %exception{helplink} -
                        %exception{data} %newline %date [%thread] %level %logger : %stacktrace{3} %newline
                        %date [%thread] %level %logger : %stacktracedetail{3} %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>
      </configuration>
   <!--End Code-->

Some notes for conversionPatterns in the config file above;

%appdomainthe friendly name of the appdomain from which the log entry was made
%datethe local datetime when the log entry was made
%exception

a formatted form of the exception object in the log entry, if the entry contains an exception; otherwise, this format expression adds nothing to the log entry
has some sub-object
%exception{message} = exp.Message
%exception{source} = exp.Source 
%exception{stacktrace} = exp.StackTrace
%exception{targetsite} = exp.TargetSite
%exception{helplink} = exp.HelpLink
%exception{data} = exp.Data //this statement needs minor development as shown below 
                    

%filethe file name from which the log entry was made; note that using %file has a significant performance impact and I don't recommend using it
%identitythe user name of the active user logging the entry; this one is less reliable than %username; note that using %identity has a significant performance impact and I don't recommend using it
%levelthe severity level of the log entry (DEBUG,INFO, etc)
%linethe source code line number from which the log entry was made; slow
%locationsome rudimentary call stack information, including file name and line number at which the log entry was made; using
%loggerthe name of the logger making the entry; more on this in a bit
%methodthe name of the method in which the log entry was made; also slow
%messagethe log message itself. 
%newlinethe value of Environment.NewLine
%timestampthe milliseconds between the start of the application and the time the log entry was made
%typethe full typename of the object from which the log entry was made
%usernamethe Windows identity of user making the log entry; slow
%utcdatethe UTC datetime when the log entry was made
%%a percent sign (%)







Second,add some reference to your code(project) for using any line you want.
a-)
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
into your main or enterance class definition as a title.
b-)
  private static readonly log4net.ILog log = log4net.LogManager.GetLogger
            (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 into your class as a member.

c-)
log.Error("string message", exception);
use it in your project world.

Important Notice:
Exception class has a "Data" member as a collection.I figured out that you can not send this collection to the appender from your source code.I added some statements  into log4net source code projects and rebuild it to use in my projects :

open log4net project from visual studio (2008 or 2010)
open log4net project > Util > ExceptionPatternConverter.cs file and focus to the "Convert" method.
add following codes to the "switch case" statement before "default"
  case "data":
                        foreach(DictionaryEntry obj in loggingEvent.ExceptionObject.Data)
                            WriteObject(writer, loggingEvent.Repository, obj.Key.ToString() + ":" + obj.Value.ToString());
                        break;


enjoy...




Comments

Popular posts from this blog

Assembly Microsoft.Dynamics.Service.Plugins.dll can not be loaded. Dynamics CRM 365 Engine version 9 - CRM User creation error

Exception caught instantiating TERADATA report server extension SQL Reporting Services

Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified at Configuration class initiation in CrmServiceHelper.cv