Simple C# Logger

This sample should show how easy it is to write a simple logger for your own needs. It will save several logs you definded by class in the logger repository so you can resolve logs from different classes just by searching one list. I think the easiest way is just to show the source code, I think it’s really easy to understand.

At first of all there should be a simple enum to represent the log types. You can add any other types of your need. Later every logger entry will get one of these types.

public enum LogType
{
   ERROR = 0,
   MESSAGE = 1,
   SUCCESS = 2,
   WARNING = 3
}

Next a Logger class is needed. The logger will need a LoggerName, in this case just the classname of the loggers usage, a list for the several entries and some methods to get back, select/sort, save and print the log entries.

public class Logger
{
   public Logger(string UniqueClassName)
{
   LoggerName = UniqueClassName;
}

   public string LoggerName { get; }

   public List<LogEntry> LogEntries = new List<LogEntry>();

public void PrintLastLogEntry()
{
   Console.WriteLine(GetFormatedLogEntry(LogEntries.Last()));
}

public void PrintAllLogEntries()
{
   foreach (var logEntry in LogEntries)
   Console.WriteLine(GetFormatedLogEntry(logEntry));
}

public string GetFormatedLogEntry(LogEntry logEntry)
{
   return $"{logEntry.DateTime}: {LoggerName} {logEntry.Type} {logEntry.Text}";
}

public void NewLogEntry(LogType logType, string text)
{
   LogEntries.Add(new LogEntry() {DateTime = DateTime.Now, Text = text, Type = logType, Logger = this});
}

public List<LogEntry> GetLogEntriesByDateTime(DateTime dateTime)
{
   return LogEntries.FindAll(o => o.DateTime == dateTime);
}

public List<LogEntry> GetLogEntriesByLogType(LogType logType)
{
   return LogEntries.FindAll(o => o.Type == logType);
}

public List<LogEntry> GetAllLogEntries()
{
   return LogEntries;
}

public LogEntry GetLastLogEntry()
{
   return LogEntries.Last();
}

public void SaveLoggerToRepo()
{
   LoggerRepository.Instance.LoggerList.Add(this);
}
}

There is still a class LogEntries needed which will represent the log entry itself with a datetime, the message, the logtype and some class methods to make life easier.

public class LogEntry
{
public Logger Logger { get; set; }
public LogType Type { get; set; }

public string Text { get; set; }

public DateTime DateTime { get; set; }

public string GetFormatedLogEntry(LogEntry logEntry)
{
   return $"{logEntry.DateTime}: {Logger.LoggerName} {logEntry.Type} {logEntry.Text}";
}

public void PrintLogEntry()
{
   Console.WriteLine(GetFormatedLogEntry(this));
}
}

And finally the LoggerRepository to hold the data. I used a singleton pattern so there won’t be more than just one instance of the repo. The really cool thing about this is the fact that you can make linq operations on always the same list.

public class LoggerRepository
{
#region singleton
public static LoggerRepository Instance
{
get { return _instance; }
}
private static readonly LoggerRepository _instance = new LoggerRepository();

private LoggerRepository()
{
}
#endregion singleton

public List<Logger> LoggerList = new List<Logger>();
}

To test the logger just try out the following.

class Program
{
static void Main(string[] args)
{
   Logger logger = new Logger(nameof(Program));
   logger.NewLogEntry(LogType.ERROR, "Something is wrong");
   logger.NewLogEntry(LogType.MESSAGE, "This is a message/info");
   logger.NewLogEntry(LogType.SUCCESS, "This totaly worked out");
   logger.NewLogEntry(LogType.WARNING, "What you did could be dangerous");
   logger.SaveLoggerToRepo();

   new TestLoggerClass();

   Console.ReadKey();
   Console.WriteLine();
   foreach (var _logger in LoggerRepository.Instance.LoggerList)
   {
      _logger.PrintAllLogEntries();
   }

   Console.ReadKey();
   Console.WriteLine();

   foreach (var _logger in LoggerRepository.Instance.LoggerList.FindAll(o => o.LoggerName == "Program"))
   {
      _logger.PrintAllLogEntries();
   }

   Console.ReadKey();
   }
}

public class TestLoggerClass
{
   Logger logger = new Logger(nameof(TestLoggerClass));
   public TestLoggerClass()
   {
      logger.NewLogEntry(LogType.MESSAGE, "New class instance init");
      logger.NewLogEntry(LogType.SUCCESS, "logger init ok");
      logger.SaveLoggerToRepo();
   }
}

You can download the whole project from my dropbox right here .

Comments are closed.