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.

  1. 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:
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Diagnostics;
    6. using System.IO;
    7. using System.Security.Permissions;
    8. namespace Common {
    9. /*This Class is used for logging messages to either a custom EventViewer or in a plain text file located on web server.*/
    10. public class Logging {#region "Variables"
    11. private string sLogFormat;
    12. private string sErrorTime;
    13. #endregion
    14. #region "Local methods"
    15. /* Write to Txt Log File*/
    16. public void WriteToLogFile(string sErrMsg) {
    17. try {
    18. //sLogFormat used to create log format :
    19. // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
    20. sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
    21. //this variable used to create log filename format "
    22. //for example filename : ErrorLogYYYYMMDD
    23. string sYear = DateTime.Now.Year.ToString();
    24. string sMonth = DateTime.Now.Month.ToString();
    25. string sDay = DateTime.Now.Day.ToString();
    26. sErrorTime = sYear + sMonth + sDay;
    27. //writing to log file
    28. string sPathName = "C:\\Logs\\ErrorLog" + sErrorTime;
    29. StreamWriter sw = new StreamWriter(sPathName + ".txt", true);
    30. sw.WriteLine(sLogFormat + sErrMsg);
    31. sw.Flush();
    32. sw.Close();
    33. } catch (Exception ex) {
    34. WriteToEventLog("MySite", "Logging.WriteToLogFile", "Error: " + ex.ToString(), EventLogEntryType.Error);
    35. }
    36. }
    Write to Event Log
    1. public void WriteToEventLog(string sLog, string sSource, string message, EventLogEntryType level) {
    2. //RegistryPermission regPermission = new RegistryPermission(PermissionState.Unrestricted);
    3. //regPermission.Assert();
    4. if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);
    5. EventLog.WriteEntry(sSource, message, level);
    6. }
    7. #endregion
    8. }
    9. }
  2. Call WriteToLogFile AND/OR WriteToEventLog with appropriate parameters in other functions as required.

  3. Build & deploy the solution. Check Windows’ event viewer or custom Log file to see if it’s working.

    Happy Coding!!!