Click here to Skip to main content
15,900,816 members
Articles / Programming Languages / C# 5.0
Tip/Trick

How to Create errorlog File in .NET using C#

Rate me:
Please Sign up or sign in to vote.
1.91/5 (3 votes)
30 Oct 2014CPOL1 min read 11.8K   2   3
This tip presents an example of errorlog file creation

Introduction

Errorlog file creation is more important when you are writing some logic in code behind. Here, I simply specify a small example to present the errorlog file creation using C#.

In .NET application, for every request it will call some codebehind method. If any unexpected exception will occur, then you log that information in one file. If any exception occurs in runtime, if you want to know then simply check the errorlog file.

Using the Code

Here, I will give a step by step explanation to create an errorlog file.

Step 1

Create one enum type that mentions logged data is information or exception:

C++
//
// create enum type
//
Public enum MessageType{Information,Exception};

Step 2

Create one class that specifies errorlog class and gets the path where errorlog information is stored.

C++
//
// create Class 
//
Public class ErrorLog{

static string LogFolder=ConfigurationManager.Appsettings["LogFolder"];
static string LogFilename="";
}

Note: Here, I am maintaining LogFolder information in web.config to be dynamic.

Step 3

Create one method that is common for log information or exception:

C++
//
// create Class 
//
Public class ErrorLog{

static string LogFolder=ConfigurationManager.Appsettings["LogFolder"];
static string LogFilename="";


Private static void LogMessage(strin Message,MessageType messageType)
  {
  strin filename=Datetime.now.Tostring("ddMMyyyy")+"_log.txt";
  if(!System.IO.Directory.Exists(LogFolder))
      {
        System.IO.Directory.CreateDirectory(Logfolder);

      }
   LogFilename=LogFolder+filename;
   string message=String.Format("\r\n{0}\t{1}\t{2}",Datetime.Now.ToLongTimeString(),messageType.Message);
   System.IO.File.AppendAllText(LogFilename,message);
   }
}

Step 4

Finally, specify the methods for exception and information:

C++
//
// create Class 
//
Public class ErrorLog{

static string LogFolder=ConfigurationManager.Appsettings["LogFolder"];
static string LogFilename="";


Private static void LogMessage(string Message,MessageType messageType)
  {
  strin filename=Datetime.now.Tostring("ddMMyyyy")+"_log.txt";
  if(!System.IO.Directory.Exists(LogFolder))
      {
        System.IO.Directory.CreateDirectory(Logfolder);
      }
   LogFilename=LogFolder+filename;
   string message=String.Format("\r\n{0}\t{1}\t{2}",Datetime.Now.ToLongTimeString(),messageType.Message);
   System.IO.File.AppendAllText(LogFilename,message);

   }

   Public static void LogError(string Message)
     {
      LogMessage(Message,MessageType.Exception);
     }

  Public Static void LogInfo(string Message)
     {
      LogMessage(Message,MessageType.Information);
     }
}

That's it. Your errorlog file is created. Now wherever you required to log exception, you simply call methods.

C++
//
// To log Information call LogInfo method
//

ErrorLog.LogInfo("Begin: Home- Index - get action: ")

//your action code come ere

ErrorLog.LogInfo("End: Home- Index - get action :");

Finally

In ASP.NET MVC, the calling code is like this:

C++
//
// To log Information call LogInfo method
//

Public ActionResult Index(){

      try{

       ErrorLog.LogInfo("Begin: Home- Index - get action: ")

        //your action code come ere

        return View();       
        }
       catch(exception ex)
        {
        ErrorLog.LogError("Exception: Home- Index - get action  "+ ex.Message)
        }

       finally{
        ErrorLog.LogInfo("End: Home- Index- get action:")
       }
}

I hope everyone understands. Try it your own way. It will be more useful.

Points of Interest

This is more useful when an unexpected exception will occur and we log that information and we check it.

History

  • 2014-10-30

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionneeds work. good start though Pin
KeithAPirkl1-Nov-14 4:34
KeithAPirkl1-Nov-14 4:34 
GeneralMy vote of 1 Pin
Wendelius30-Oct-14 6:32
mentorWendelius30-Oct-14 6:32 
QuestionWill this work in a multi-user environment ? It does not look like the fileaccess to your logfile is threadsafe. Pin
Marc Koutzarov30-Oct-14 3:33
professionalMarc Koutzarov30-Oct-14 3:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.