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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- using System.IO;
- using System.Security.Permissions;
-
- namespace Common {
-
-
- public class Logging {#region "Variables"
-
- private string sLogFormat;
- private string sErrorTime;
-
- #endregion
-
-
- #region "Local methods"
-
-
- public void WriteToLogFile(string sErrMsg) {
- try {
-
-
- sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
-
-
-
- string sYear = DateTime.Now.Year.ToString();
- string sMonth = DateTime.Now.Month.ToString();
- string sDay = DateTime.Now.Day.ToString();
- sErrorTime = sYear + sMonth + sDay;
-
-
- 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) {
-
-
-
- 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!!!