In many of our .NET projects, we need to log exceptions/errors/information in either Windows event log or a custom text Log file for debugging/review/reporting purposes. Here is a generic class written for logging, you can use this class to any of your C# .NET projects and use WriteToLogFile OR WriteToEventLog methods wherever required in you code.
- To achieve this, add ‘Common’ folder or project in your visual studio solution.
Add a class file named ‘Logging’ and use the following code. Make sure to add all the required reference assemblies.
Code:Write to Event Log- 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.*/
- 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);
- }
- }
- 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
- }
- }
- Call WriteToLogFile AND/OR WriteToEventLog with appropriate parameters in other functions as required.
- Build & deploy the solution. Check Windows’ event viewer or custom Log file to see if it’s working.
Happy Coding!!!

Vipul MalhotraPosted Sep 26, 2015, 4:05 AM
nice
Santhakumar MunuswamyPosted Sep 25, 2015, 2:11 PM
Good Article
Sujeet SumanPosted Sep 25, 2015, 12:30 PM
Nice Article.............
Nilesh JadavPosted Sep 25, 2015, 9:39 AM
Nice one sir !!
Shakti SaxenaPosted Sep 25, 2015, 9:09 AM
good one
Saineshwar BageriPosted Sep 25, 2015, 8:31 AM
Nice one