google analytics

Friday, November 13, 2009

.NET application logging with Log4net in Console , File & Database

Hello All

Today I will go through logging with Log4net. Log4Net is a logging framework ( a rich library) for .NET. Log4Net is popular for its simplicity and robustness. We can write log in various way though we generally write log only in file we we can also mail log, show in console,save in datatbase as well as write in file in different ways.

First we have to download the Log4Net and add the log4net.dll in our implementation project. In the example I have take 2 projects named LogWriter and LogRunner accordingly, In one project I have implemented the logging and in another I execute that logging method.

My project structure is as image bellow :

In the LogWriter I have take two class as bellow :

LogLevel.cs: In this class I simply define a enum which basically helps to define my log level in my LogUtil class.

namespace LogWriter
{
    public enum LogLevel
    { 
        DEBUG,
        ERROR,
        FATAL,
        INFO,
        WARN    
    }
}

LogUtil.cs: In this class I have a static method named WriteLog which take 2 parameters one define log level and another take log message as string.

using log4net;
using log4net.Config;

namespace LogWriter
{
    public static class LogUtil
    {
        private static ILog logger = LogManager.GetLogger(typeof(LogUtil));

        static LogUtil()
        {
            XmlConfigurator.Configure();
        }

        public static void WriteLog(LogLevel logLevel,string log)
        {
            if (logLevel.Equals(LogLevel.DEBUG))
            {
                logger.Debug(log);
            }
            else if (logLevel.Equals(LogLevel.ERROR))
            {
                logger.Error(log);
            } 
            else if (logLevel.Equals(LogLevel.FATAL))
            {
                logger.Fatal(log);
            } 
            else if (logLevel.Equals(LogLevel.INFO))
            {
                logger.Info(log);
            } 
            else if (logLevel.Equals(LogLevel.WARN))
            {
                logger.Warn(log);
            }             
        
        }
    }
}

As I am writing a  console application so my mail runner file is Program.cs which is as bellow but you can follow the same procedure in different place as per you requirement.

using System;
using LogWriter;

namespace LogRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            try {
                throw new Exception();
            }

            catch (Exception exc)
            {
                    LogUtil.WriteLog(LogLevel.DEBUG, "Debug mode logging");
                    LogUtil.WriteLog(LogLevel.ERROR, "Error mode logging");
                    LogUtil.WriteLog(LogLevel.FATAL, "Fatal mode logging");
                    LogUtil.WriteLog(LogLevel.INFO, "Info mode logging");
                    LogUtil.WriteLog(LogLevel.WARN, "Warn mode logging");
    
                    Console.ReadKey();
            }
        }
    }
}

Now one of the most important thing I will focus is log4net configuration. We can configure it from web.config or app.config . In my example I have configured it app.config file in my LogRunner project. In the app.config file follow the commented section.

My configuration file is as bellow , please go through the commented line to get know in detail such as log file rolling, max log file number & size, Log level etc.
<?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">

            <!-- Log file locaation -->
            
            <param name="File" value="C:\Users\sanzeeb\Documents\Visual Studio 2008\Projects\Solution1\LogWriter\Log\" />

            <param name="AppendToFile" value="true" />

            <!-- Maximum size of a log file -->
            <maximumFileSize value="2KB" />

            <!--Maximum number of log file -->
            <maxSizeRollBackups value="8" />

            <!--Set rolling style of log file -->
            <param name="RollingStyle" value="Composite" />

            <param name="StaticLogFileName" value="false" />

            <param name="DatePattern" value=".yyyy-MM-dd.lo\g" />

            <layout type="log4net.Layout.PatternLayout">

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

        <!-- Appender layout fix to view in console-->
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >

            <layout type="log4net.Layout.PatternLayout">

                <param name="Header" value="[Header]\r\n" />

                <param name="Footer" value="[Footer]\r\n" />

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

      
        <!-- Database appender -->

        <!--
        You need to create a table as bellow to insert log in database for MSSQL server.
        
        CREATE TABLE [dbo].[Log] (
        [Id] [int] IDENTITY (1, 1) NOT NULL,
        [Date] [datetime] NOT NULL,
        [Thread] [varchar] (255) NOT NULL,
        [Level] [varchar] (50) NOT NULL,
        [Logger] [varchar] (255) NOT NULL,
        [Message] [varchar] (4000) NOT NULL,
        [Exception] [varchar] (2000) NULL
        )
        -->

        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <bufferSize value="100" />
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="Data Source=SANZEEB-PC\SQLEXPRESS;Initial Catalog=AppTesterDB;Integrated Security=True" />
            <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
            <parameter>
                <parameterName value="@log_date" />
                <dbType value="DateTime" />
                <layout type="log4net.Layout.RawTimeStampLayout" />
            </parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%thread" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="50" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%level" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%logger" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="4000" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%message" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@exception" />
                <dbType value="String" />
                <size value="2000" />
                <layout type="log4net.Layout.ExceptionLayout" />
            </parameter>
        </appender>

        <root>

            <level value="DEBUG" />

            <!--
            Log level priority in descending order:
            
            FATAL = 1 show  log -> FATAL 
            ERROR = 2 show  log -> FATAL ERROR 
            WARN =  3 show  log -> FATAL ERROR WARN 
            INFO =  4 show  log -> FATAL ERROR WARN INFO 
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->

            <!—To write log in file -->
            <appender-ref ref="LogFileAppender" />

            <!--To view log in console -->
            <appender-ref ref="ConsoleAppender" />
            
            <!--To write log in file batabase -->
            <appender-ref ref="AdoNetAppender" />

        </root>

    </log4net>

</configuration>

Hope this will help to improve your logging in your .NET application.

Thanks

That’s all for today.

BYE

Friday, August 21, 2009

ULM Class Diagram

Hello All

Today I will go through with UML class diagram. It’s like old wine in old bottle ;) . We all know that these are very basic but now a days people just stat to do coding without making any class or activity diagram, so eventually they fall in a design related issue if the system becomes huge.

Again UML is more impotent to understand any complex system which is properly documented in UML diagram.UML makes our life simple through notifying us the design fault.

So let’s start the old song again.

Class:

Generally there are 3 components in the class icon as following.

1. Class Name

2. Attributes

3. Functions / Methods

Visibility:

Visibility of class diagram represents the accessibility of the class members. Visibility notations are as bellow .

Notations

Access type

-

Private

+

Public

~

Protected

Association:

When two objects are connected with each other then it can be represent as association. For students and seminar we can use association notation where students are attending in seminar.

Multiplicity Indicators:

Multiplicity indicates the countable objects relation with other objects.

Indicator

Meaning

0..1

Zero or one

1

One only

0..*

Zero or more

1..*

One or more

n

Only n (where n > 1)

0..n

Zero to n (where n > 1)

1..n

One to n (where n > 1)

Composition:

Composition represents with a black diamond. It represents that a component strongly depends on another component. Suppose we have two objects one is circle and another is point. In that case a circle consists of many points.

Aggregation:

When an object form with another object(s) but not mandatory to form the main object then its denoted by a diamond. Suppose student and school object can represent with aggregation relationship.

Inheritance:

When one object inherits property from any parent object then the sign denoted with a triangle shape arrow.

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.

Saturday, July 25, 2009

Agile Scrum and traditional software development ( SDLC ) terms.

Hello All

Few days back our boss focused on how to map the traditional software development term with Agile development term as a result I think it will be a good topic to discus and share our thoughts. We Agile practitioner always use some terms such as sprint, product backlog, burn-down chart etc. But people who are not used to Agile can hardly understand these terms where as these things are similar as traditional SDLC terms.

Today I will try to focus some of this Agile terms and try to make a equivalent SDLC terms, so that people can adopt the Agile practice easily.

In this post I will follow Scrum framework for the Agile development. There are some other Agile framework such as AUP,XP,FDD etc.

Agile Development Process:

In the following picture (it’s an Agile development process) we can see some agile terms such as Product backlog, Sprint Backlog, sprint and there are also some other terms like product owner, scrum master, daily scrum meeting, velocity, retrospective etc.

Roles:

Product Owner: Product owner is the client. According to their order the software will develop and they will clarify the requirement for the developers so that developers can develop the exact efficient software for the customer.

Scrum Master: Scrum master plays a similar type of role as project manager. But as the Agile team is self organized so scrum master doesn’t involve deeply in a project as traditional project manager. Scrum master takes initiative on the impediments and managing the process working perfectly so that the goal meets in the desired time frame (sprint).

Teams: In general a team means group of self organized developers who will develop the software.

Projects Terms:

Product backlog: Product backlog is the collection of requirements of a system. This requirements are placed according to the development priority, so that the high priority requirements are develop in the early phases.

Sprint: Sprint is like the time frame of an incremental development process. In a sprint the team fixes what to do in this cycle and deployment. Developers develop a deliverable product in a sprint and deploy it in client end. Once the tasks are fixed for a sprint the developer should not be interrupt with additional requirement and mass requirement change. If it’s necessary, the tasks will add in product backlog with high priority so that they can add in next sprint’s planning.

Sprint backlog: Sprint backlog is the set of high priority tasks taken from the set of product backlog which will develop in the current sprint and deploy in client end.

Scrum meeting: Scrum meeting is a daily short standing meeting where each team member will express what problem(s) s/he has faced last day and what s/he will do today. This meeting is extremely focused.

Retrospective: At the last day the team will discussed what went good what went band and what are the opportunity so that in the next sprint they can take initiative according to the retrospective.

Burndown chart: There are different types of burndown charts. Which represents the development process through graph, so that an Agile team member can get to know what project’s condition in a simple view.

Velocity: An agile team can estimate how much effort they can put in product backlog for one sprint. This velocity is determined from previous sprint’s average data. This velocity can be used to predict the project effort planning and team's productivity .

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.