Logger in C# - An easy way for monitoring .NET applications






4.62/5 (31 votes)
Apr 14, 2003
2 min read

481057

8934
Logger is used to create a customized error log file or an error can be registered as a log entry in the Windows Event Log on the administrator's machine with ON/OFF logging facility.
Windows event log
Customized event log
Overview
Logger is used for creating customized error log files or an error can be registered as a log entry in the Windows Event Log on the administrator's machine. This article is demonstrating how to create a text based error log file along with error messages with your own format, using a C# class.
This class demonstrates the use of following namespaces.
System.IO
System.Net
System.Diagnostics
System.Xml
Installation step
Just download , add reference to your application, write single line of code in your application to use it.
Source code
This project will handle the following two steps:
- Creating customized error log file capturing for our application errors.
- Register the errors in Windows event log on the administrator's machine.
You can use any one of these error capturing mechanisms to monitor your applications.
The main idea is create a error log file based on input [path] we have given. If the file is not available, then Logger will create a log file named LogFile.txt under application directory. If the file is available, the it will update the error info into that file with necessary information.
using System.IO;
using System.Net;
using System.Diagnostics;
Before we make a function
to create an error file, we
have to declare some variables that will be used in our function. This is an
example of variables
declaration and the main function is
ErrorRoutine
.
public static string strLogFilePath = string.Empty;
private static StreamWriter sw = null;
/// <summary>
/// Setting LogFile path. If the logfile path is
/// null then it will update error info into LogFile.txt under
/// application directory.
/// </summary>
public string LogFilePath
{
set
{
strLogFilePath = value;
}
get
{
return strLogFilePath;
}
}
/// <summary>
/// Write error log entry for window event if the bLogType is true.
/// Otherwise, write the log entry to
/// customized text-based text file
/// </summary>
/// <param name="bLogType"></param>
/// <param name="objException"></param>
/// <returns>false if the problem persists</returns>
public static bool ErrorRoutine(bool bLogType,Exception objException)
{
try
{
//Check whether logging is enabled or not
bool bLoggingEnabled = false;
bLoggingEnabled = CheckLoggingEnabled();
//Don't process more if the logging
if (false == bLoggingEnabled)
return true;
//Write to Windows event log
if (true == bLogType)
{
string EventLogName = "ErrorSample";
if (!EventLog.SourceExists(EventLogName))
EventLog.CreateEventSource(objException.Message,
EventLogName);
// Inserting into event log
EventLog Log = new EventLog();
Log.Source = EventLogName;
Log.WriteEntry(objException.Message,
EventLogEntryType.Error);
}
//Custom text-based event log
else
{
if (false == CustomErrorRoutine(objException))
return false;
}
return true;
}catch(Exception)
{
return false;
}
}
Here, LogFilePath
property is used set the error log
file path, where we want to create/reside that file. The main function ErrorRoutine
will take two parameters. First one is Boolean
, to decide window event log or customized error log. The
parameter bLogType = true
capture error information using
Windows event log on the administrator's machine. Otherwise, error information
will update in to text file.
///<summary>
/// If the LogFile path is empty then, it will write the log entry to
/// LogFile.txt under application directory.
/// If the LogFile.txt is not availble it will create it
/// If the Log File path is not empty but the file is
/// not availble it will create it.
/// <param name="objException"></param>
/// <RETURNS>false if the problem persists</RETURNS>
///</summary>
private static bool CustomErrorRoutine(Exception objException)
{
string strPathName = string.Empty ;
if (strLogFilePath.Equals(string.Empty))
{
//Get Default log file path "LogFile.txt"
strPathName = GetLogFilePath();
}
else
{
//If the log file path is not empty but the file
//is not available it will create it
if (true != File.Exists(strLogFilePath))
{
if (false == CheckDirectory(strLogFilePath))
return false;
FileStream fs = new FileStream(strLogFilePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Close();
}
strPathName = strLogFilePath;
}
bool bReturn = true;
// write the error log to that text file
if (true != WriteErrorLog(strPathName,objException))
{
bReturn = false;
}
return bReturn;
}
/// <summary>
/// Write Source,method,date,time,computer,error
/// and stack trace information to the text file
///
/// <param name="strPathName"></param>
/// <param name="objException"></param>
/// <RETURNS>false if the problem persists</RETURNS>
///</summary>
private static bool WriteErrorLog(string strPathName,
Exception objException)
{
bool bReturn = false;
string strException = string.Empty;
try
{
sw = new StreamWriter(strPathName,true);
sw.WriteLine("Source : " +
objException.Source.ToString().Trim());
sw.WriteLine("Method : " +
objException.TargetSite.Name.ToString());
sw.WriteLine("Date : " +
DateTime.Now.ToLongTimeString());
sw.WriteLine("Time : " +
DateTime.Now.ToShortDateString());
sw.WriteLine("Computer : " +
Dns.GetHostName().ToString());
sw.WriteLine("Error : " +
objException.Message.ToString().Trim());
sw.WriteLine("Stack Trace : " +
objException.StackTrace.ToString().Trim());
sw.WriteLine("^^------------------------
-------------------------------------------^^");
sw.Flush();
sw.Close();
bReturn = true;
}
catch(Exception)
{
bReturn = false;
}
return bReturn;
}
/// <summary>
/// Check the log file in applcation directory.
/// If it is not available, creae it
///
/// <RETURNS>Log file path</RETURNS>
///</summary>
private static string GetLogFilePath()
{
try
{
// get the base directory
string baseDir = AppDomain.CurrentDomain.BaseDirectory +
AppDomain.CurrentDomain.RelativeSearchPath;
// search the file below the current directory
string retFilePath = baseDir + "//" + "LogFile.txt";
// if exists, return the path
if (File.Exists(retFilePath) == true)
return retFilePath;
//create a text file
else
{
if (false == CheckDirectory(strLogFilePath))
return string.Empty;
FileStream fs = new FileStream(retFilePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Close();
}
return retFilePath;
}
catch(Exception)
{
return string.Empty;
}
}
/// <summary>
/// Create a directory if not exists
///
/// <param name="stLogPath"></param>
///<summary> <RETURNS></RETURNS>
private static bool CheckDirectory(string strLogPath)
{
try
{
int nFindSlashPos = strLogPath.Trim().LastIndexOf("\\");
string strDirectoryname =
strLogPath.Trim().Substring(0,nFindSlashPos);
if (false == Directory.Exists(strDirectoryname))
Directory.CreateDirectory(strDirectoryname);
return true;
}
catch(Exception)
{
return false;
}
}
ON/OFF logging
If you place LogginStaus.Config under application folder [\bin\debug or project] of your project then Logger read it's value to enable/disable logging. If the file is not available then enable the logging by default.
The LogginStatus.Config looks like this.
<?xml version="1.0" encoding="utf-8" ?>
<LoggingStatus>
<LoggingEnabled>0</LoggingEnabled>
</LoggingStatus>
0 for disable logging
1 for enable logging
/// <summary>
/// Check Logginstatus config file is exist.
/// If exist read the value set the loggig status
/// </summary>
private static bool CheckLoggingEnabled()
{
string strLoggingStatusConfig = string.Empty;
strLoggingStatusConfig = GetLoggingStatusConfigFileName();
//If it's empty then enable the logging status
if (strLoggingStatusConfig.Equals(string.Empty))
{
return true;
}
else
{
//Read the value from xml and set the logging status
bool bTemp = GetValueFromXml(strLoggingStatusConfig);
return bTemp;
}
}
/// <summary>
/// Check the Logginstatus config under debug or
/// release folder. If not exist, check under
/// project folder. If not exist again, return empty string
/// </summary>
/// <RETURNS>empty string if file not exists</RETURNS>
private static string GetLoggingStatusConfigFileName()
{
string strCheckinBaseDirecotry =
AppDomain.CurrentDomain.BaseDirectory+
"LoggingStatus.Config";
if (File.Exists(strCheckinBaseDirecotry))
return strCheckinBaseDirecotry;
else
{
string strCheckinApplicationDirecotry =
GetApplicationPath() + "LoggingStatus.Config";
if (File.Exists(strCheckinApplicationDirecotry))
return strCheckinApplicationDirecotry;
else
return string.Empty;
}
}
///<summary>
/// Read the xml file and getthe logging status
/// <param name="strXmlPath"></param>
///</summary> <RETURNS></RETURNS>
private static bool GetValueFromXml(string strXmlPath)
{
try
{
//Open a FileStream on the Xml file
FileStream docIn = new FileStream(strXmlPath,
FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
XmlDocument contactDoc = new XmlDocument();
//Load the Xml Document
contactDoc.Load(docIn);
//Get a node
XmlNodeList UserList =
contactDoc.GetElementsByTagName("LoggingEnabled");
//get the value
string strGetValue= UserList.Item(0).InnerText.ToString();
if (strGetValue.Equals("0"))
return false;
else if (strGetValue.Equals("1"))
return true;
else
return false;
}
catch(Exception)
{
return false;
}
}
To use this class, Just add a reference to your project and follow the steps
and just import the Logger
reference into you project.
This is a code behind C# for this page, I call the ErrorRoutine
function from our class when exception is occurred.
Writing log entry to customized text file:
using Logger;
.
.
.
private void BtnFind_Click(object sender, System.EventArgs e)
{
try
{
int i = 1;
int j = 0;
int k = i/j;
}
catch(Exception ee)
{
bool bReturnLog = false;
ErrorLog.LogFilePath = "F:\\DotNetProjects\\
SampleLogFile\\ErrorLogFile.txt";
//false for writing log entry to customized text file
bReturnLog = ErrorLog.ErrorRoutine(false,ee);
if (false == bReturnLog)
MessageBox.Show("Unable to write a log");
}
}
This is a code behind VB.NET for this page. Writing log entry to Windows event log:
Imports Logger;
.
.
.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim i, j, k As Integer
i = 1
j = 0
k = i / j
Catch ex As Exception
Dim bReturnLog As Boolean
//True for writing log entry to windows event log
bReturnLog = ErrorLog.ErrorRoutine(True,ex)
If (False == bReturnLog) Then
MessageBox.Show("Unable to write a log")
End If
End Try
End Sub
That's it. :-) You can use this for console, Winforms and web forms too.