C# EVENT LOGGER

#20 C# EVENT LOGGER

Event Logger Example

A simple logger to write all the occurring events to a file in the root directory \ Logs folder of the application.

The logger class LoggerClass.cs processes the data and writes it to a .log file. the Class can also delete the current log file which is being written to.

 public static class Logger
        {
            private static string LogFile = Application.StartupPath + "\\Logs\\Event_Logger_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".log";

            public static void WriteLine(string txt)
            {
                try
                {
                    File.AppendAllText(LogFile, "[" + DateTime.Now.ToString() + "] : " + txt + "\n");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Could Not Append Text To Log File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            public static void DeleteLog()
            {
                try
                {
                    File.Delete(LogFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Could Not Delete Log File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *