Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Easiest Way of logging in .Net
Posted By Sarin on Dec 24, 2012     RSS Feeds     Latest Hinduism news
3127 Views

In .net, while you develop an application, you have many ways to know how the application is functioning. You can debug through the code, insert breakpoints, write unit cases etc. But once your code is live into the production server, you cannot track your application using the above means. You must have some efficient framework to track the inconsistencies, errors and warnings your application is generating. Although the windows operating system keeps generating information, messages, errors, warnings related to your application, still there is a need to store more detailed information about your application activities. The simplest way to track your application is logging. You may log a completion of an activity, task or function; you may log an error, warning, message etc. There are many frameworks available for logging. But it needs some times understanding and setting up such logging framework on your system. Though such framework is very useful for huge applications, I don’t recommend using such framework for small application. I have developed many small applications for maintaining contents of my website. Setting up a logging framework for such small applications seems to be a time of waste. So, I use a very simple standard inbuilt logging technique for logging my application errors.
I use the .Net function of writing onto files for generating log. Below is the function I use to create log in small applications.
  
public static void CreateErrorLog(string error)
         {
            try
             {
                string sErrorDir = System.Configuration.ConfigurationManager.AppSettings["ErrorPath"].ToString();
                DirectoryInfo dir = new DirectoryInfo(sErrorDir);
                if (!dir.Exists)
                    dir.Create();
      string LogFileName = sErrorDir + "/ErrorLog_" + DateTime.Today.ToString("dd-MMM-yyyy")+".log";
                StreamWriter sw = new StreamWriter(LogFileName, true);
                error = DateTime.Now.ToLongTimeString()+ " ==> " + error;
                sw.WriteLine(error);
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
            catch (Exception ex)
             {
                throw new Exception("Error in Creating Log File. Reason: "+ex.Message);
            }
        }

Above function creates a log file in the format ErrorLog_{Date}.Log at the path prescribed in Key “Errorpath” of app.,config file. Every day, a new log is created at this location to make tracking easier. For a demo, I will generate an error log using the below code.
  
  try
             {
                decimal fv = Convert.ToDecimal("1/0");
                Console.WriteLine("Output : " + fv.ToString());
            }
            catch (Exception ex)
             {
                //CreateErrorLog("Error Message:"+ex.Message);
                CreateErrorLog("Error Message : " + ex.Message + Environment.NewLine + "Error StackTrace : " + ex.StackTrace);
                Console.WriteLine("Error : " + ex.Message);
            }

When I run the application, an error log is created at c:\ as shown below

  
On executing the application couple of times, the following log was generated in the log files
  

Please navigate to the end of this article for sample source code.
  
This must be the easiest way of generating log files for small applications. If you are looking for some advanced logging framework, then below are some of them (I personally prefer Log4net)
  1)    Log4Net
2)    Microsoft Enterprise Library
3)    C# logger
4)    NLog
    5)   GIBRALTAR
6)    Object Guy's Logging Framework
7)    Log4Free
8)    CuttingEdge
9)    Crypto Logger

Some of the Advantages of this logging framework are:
      1)    Logging Level: Provides different logging level to differentiate type of log. Common logging levels used in almost all logging framework are  
      a)    Fatal - it's an error that will most probably result in application crashing
b)    Error - it's a severe error that can cause application crashing
c)    Warning - indicates a situation that can potentially lead to more serious errors
d)    Info - information that can be useful in application tracing
e)    Debug - message that has critical information for application tracing
  
        2)    Logging Category: Logging categories helps you define different categories of your log. For example, you can create a separate log for each module of your application so that the error tracking and the subsequent bug fixing is made easier.
3)     Logging Format: Some logging Framework gives you a flexibility of logging in different types of files. Most commonly logging file for logging is using text files. But few frameworks gives you an flexibility of logging file in XML, Excel, Database, .MDB Files etc.
4)    Log viewing made easier. These frameworks provide inbuilt tools to simplify viewing your file. For example, tool will show the log in three columns : First will be Error type, Second Error message and third Stack trace
5)    Some tools provide logging at even interface level with the flexibility of skipping logging at some pre-defined namespace or class level.
6)    This framework provide a non-blocking, thread safe logging framework, it also includes a web service to collect logs, email notifications, and an analysis tool with extensive filtering and graphing capabilities. These frameworks also provide detailed graphical descriptions of your application errors with metrics and performance parameters.
7)    Can be integrated across multiple cross platform applications using TCP or HTTP protocol
      
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Related Articles
Visitors-Hits counter for your website
Why and how to create RSS feeds in C#
Nested Transaction, SavePoint and error handling in sql server
Silverlight New features & system requirement
What is Silverlight,its features and how it works
Simple silver light sample application
Show catchy cool tool-tips with Ajax
Easiest Way of logging in .Net

Post Comment