Wednesday, April 13, 2011

Error & information logging; event viewer or text file

We can log different errors or information while writing code for any .NET application, here is a generic class written for logging:

Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;

namespace Common
{
/*This Class is used for logging messages to either a custom EventViewer or in a plain text file located on web server.
* Owner : Deepak Solanki
* Year : 2011 */

public class Logging
{
#region "Variables"

private string sLogFormat;
private string sErrorTime;

#endregion


#region "Local methods"

/* Write to Txt Log File*/
public void WriteToLogFile(string sErrMsg)
{
try
{
//sLogFormat used to create log format :
// dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";

//this variable used to create log filename format "
//for example filename : ErrorLogYYYYMMDD
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString();
string sDay = DateTime.Now.Day.ToString();
sErrorTime = sYear + sMonth + sDay;

//writing to log file
string sPathName = "C:\\Logs\\ErrorLog" + sErrorTime;
StreamWriter sw = new StreamWriter(sPathName + ".txt", true);
sw.WriteLine(sLogFormat + sErrMsg);
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
WriteToEventLog("MySite", "Logging.WriteToLogFile", "Error: " + ex.ToString(), EventLogEntryType.Error);
}
}

/* Write to Event Log*/
public void WriteToEventLog(string sLog, string sSource, string message, EventLogEntryType level)
{
//RegistryPermission regPermission = new RegistryPermission(PermissionState.Unrestricted);
//regPermission.Assert();

if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);

EventLog.WriteEntry(sSource, message, level);
}

#endregion
}
}


Happy Coding!!!

No comments:

Post a Comment