Tuesday, 3 March 2020

Logging using log4net

Logging using log4net


Step : 1 

Create Demo application like console application.

Step : 2

Add log4Net library from nuget manager.

Step : 3

Add config file for log4net


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender"
                    type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="E:\Test Application\Log\log.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="2" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern"
             value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
        <conversionPattern
             value="%newline%newline%date %newline%logger 
                       [%property{NDC}] %newline>> %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>  


Step : 5

Add one class for logging method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LoggingTest
{
    public static class Logger
    {
        private static log4net.ILog Log { get; set; }

        static Logger()
        {
            Log = log4net.LogManager.GetLogger(typeof(Logger));
        }

        public static void Error(object msg)
        {
            Log.Error(msg);
        }

        public static void Error(object msg, Exception ex)
        {
            Log.Error(msg, ex);
        }

        public static void Error(Exception ex)
        {
            Log.Error(ex.Message, ex);
        }

        public static void Info(object msg)
        {
            Log.Info(msg);
        }
    }
}


Step : 6

Register config file into application assembly (Properties >> AssemblyInfo.cs).


[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]





Step : 7

Use logger method as like uses.

class Program
    {
        static void Main(string[] args)
        {
           
            try
            {
                throw new Exception("Test Logging  by dot net by vickypedia");
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            Console.WriteLine("Test Logging  by dot net by vickypedia");
            Console.ReadKey();

        }
    }



Step :8 

See the log file as mention into config "E:\Test Application\Log\log.txt"











No comments:

Post a Comment

Factorial of a Number

Recently Viewed