Pages

Monday, November 14, 2011

Log4Net Database Logging

This time i was trying to implement Database logging with log4net. as all do i search it in google for the reference :), after putting some effort i started working on that.
As we all know that Log4net is very nice open source for logging and used in almost every software development industries.
I am putting step by step solution in two parts for your refrence.
part1 part2

Happy Coding !!

Log4NetDatabaseConfiguration Part2

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

Step 5 : add New Console project for POC (LoggingExample) and add 2 config files . app.config and log4net.config
appconfig; put the configuration and modified it for the databse connection string

 
  
 

 
log4net.config:put the configuration

  
    
      
      
      
      
      
        
        
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
      


    
    
      
      
    
  


You are almost done for POC . Just two Steps Remening
Step: 6 . Create Table in Database
DROP TABLE [dbo].[ApplicationLog]
CREATE TABLE [dbo].[ApplicationLog] 
(
 [Id] int IDENTITY (1, 1) NOT NULL,
 [Date] datetime NOT NULL,
 [Thread] varchar(255) NULL,
 [Level] varchar(50) NOT NULL,
 [Logger] varchar(255) NOT NULL,
 [Host] varchar(50) NOT NULL,
 [Message] varchar(4000) NOT NULL,
 [Exception] varchar(2000) NULL,
 [severity] varchar(255) NULL,
 [useranme] varchar(255) NULL,
 [applicationName] varchar(255) NULL

)

Step:7 In Console application
using System;
using Database;

namespace LoggingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            
            
                ILogger logger = new Logger();

                logger.EnterMethod("Main");
                logger.LogInfoMessage("LogInfo");
                logger.LogError("ErrorLog");
                logger.LeaveMethod("Main");
                       
        }
    }
}
You are done now !! if you like it please put a comment.
 Hope this will help you  :)

Log4NetDatabaseConfiguration Part1

step 1. Create a New Solution  and a Class library project called 'DatabaseLogger'

step 2. Download Log4net from  here and    and after download ,find log4net-1.2.11\bin\net\2.0\release\log4net.dll and refer it to your project

step 3. create a class Called Logger and an Inerface ILogger
using System;
using System.Configuration;
using System.Globalization;
using log4net;
using System.Diagnostics;

namespace DatabaseLogger
{
    public class DbLogger : IDbLogger
    {
        #region Datamembers

        private static ILog log = null;
        private const string Log4netConnectionString = "Log4netConnectionString";

        #endregion

        #region Class Initializer        
        public Logger()
        {
            log = LogManager.GetLogger(typeof(DbLogger));
            log4net.GlobalContext.Properties["host"] = Environment.MachineName;
            log4net.GlobalContext.Properties["severity"] = "Low";
            log4net.GlobalContext.Properties["userName"] = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            log4net.GlobalContext.Properties["applicationName"] = Process.GetCurrentProcess().ProcessName;
            
        }

        #endregion

        #region IDbLogger Members

        public void EnterMethod(string methodName)
        {
            if (log.IsInfoEnabled)
                
                log.Info(string.Format(CultureInfo.InvariantCulture, "Entering Method {0}", methodName));
        }

        public void LeaveMethod(string methodName)
        {
            if (log.IsInfoEnabled)
                log.Info(string.Format(CultureInfo.InvariantCulture, "Leaving Method {0}", methodName));
        }

        public void LogException(Exception exception)
        {
            if (log.IsErrorEnabled)
                log.Error(string.Format(CultureInfo.InvariantCulture, "{0}", exception.Message), exception);
        }

        public void LogError(string message)
        {
            if (log.IsErrorEnabled)
                
                log.Error(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }

        public void LogWarningMessage(string message)
        {
            if (log.IsWarnEnabled)
                log.Warn(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }

        public void LogInfoMessage(string message)
        {
            if (log.IsInfoEnabled)
                
                log.Info(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }

        #endregion 
    }
}


using System;

namespace DatabaseLogger
{
    public interface IDbLogger
    {
        /// 
        /// Writes a log entry when entering the method.
        /// 
        /// 



Name of the method.
void EnterMethod(string methodName);

        /// 
        /// Writes a log entry when leaving the method.
        /// 
        /// 



Name of the method.
void LeaveMethod(string methodName);

        /// 
        /// Logs the exception.
        /// 
        /// 



The exception.
void LogException(Exception exception);

        /// 
        /// Logs the error.
        /// 
        /// 



The message.
void LogError(string message);

        /// 
        /// Logs the warning message.
        /// 
        /// 



The message.
void LogWarningMessage(string message);

        /// 
        /// Logs the info message.
        /// 
        /// 



The message.
void LogInfoMessage(string message);
    }
}
Step 4: Now We Need to add One more Class Call SqlServerAppender for Log4Net Connection string

using System;
using System.Configuration;
using log4net.Appender;

namespace Database
{
    public class SqlServerAppender : AdoNetAppender
    {
        private const string Log4netConnectionString = "Log4netConnectionString";

        public new string ConnectionString 
        {
            get { return base.ConnectionString; }
            set { base.ConnectionString = ConfigurationManager.ConnectionStrings[Log4netConnectionString].ConnectionString; }
        }
    }
}

after that Your Dll is ready for Refernceing for your Project where you want to implement it .
Now You need Some Configuration for Log4net and what database field you want in the table
I put  four custom fileds alogin with the other filed provieded by Log4net.
I seperated my appconfig file and log4net config file for better understatding.
for seprating you need to add a line of code  in AssembblyInfo.cs continue with part2

Wednesday, November 9, 2011

Hi friends .. I just wanted to share you that I got a very good site for the live session on Microsoft Technologies this site has already started since 13jan2011 . many of you guys may be know about that but still i would like to sahre this site . Lots of webcast are there in microsoft technologies.
Link : Zeoller
may be this will help you little ..