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;
public string LogFilePath
{
set
{
strLogFilePath = value;
}
get
{
return strLogFilePath;
}
}
public static bool ErrorRoutine(bool bLogType,Exception objException)
{
try
{
bool bLoggingEnabled = false;
bLoggingEnabled = CheckLoggingEnabled();
if (false == bLoggingEnabled)
return true;
if (true == bLogType)
{
string EventLogName = "ErrorSample";
if (!EventLog.SourceExists(EventLogName))
EventLog.CreateEventSource(objException.Message,
EventLogName);
EventLog Log = new EventLog();
Log.Source = EventLogName;
Log.WriteEntry(objException.Message,
EventLogEntryType.Error);
}
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.
private static bool CustomErrorRoutine(Exception objException)
{
string strPathName = string.Empty ;
if (strLogFilePath.Equals(string.Empty))
{
strPathName = GetLogFilePath();
}
else
{
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;
if (true != WriteErrorLog(strPathName,objException))
{
bReturn = false;
}
return bReturn;
}
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;
}
private static string GetLogFilePath()
{
try
{
string baseDir = AppDomain.CurrentDomain.BaseDirectory +
AppDomain.CurrentDomain.RelativeSearchPath;
string retFilePath = baseDir + "//" + "LogFile.txt";
if (File.Exists(retFilePath) == true)
return retFilePath;
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;
}
}
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";
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.