Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created February 3, 2012 11:23
Show Gist options
  • Save hanssens/1729739 to your computer and use it in GitHub Desktop.
Save hanssens/1729739 to your computer and use it in GitHub Desktop.
[C#] Simple Logger
namespace Hanssens.Tools
{
public enum LogTypes
{
/// <summary>
/// The default message type.
/// </summary>
Info,
Debug,
Error,
Warning
}
public interface ILogger
{
void Write(string message);
void Write(string message, LogTypes logType);
void Write(LogLine logLine);
void Flush();
}
public abstract class BaseLogger : ILogger, IDisposable
{
public List<LogLine> Lines { get; private set; }
public BaseLogger()
{
Lines = new List<LogLine>();
}
public virtual void Write(string message)
{
Write(message, LogTypes.Info);
}
public virtual void Write(string message, LogTypes logType)
{
Write(new LogLine()
{
Message = message,
LogType = logType
});
}
public virtual void Write(LogLine logLine)
{
Lines.Add(logLine);
}
public abstract void Flush();
public void Dispose()
{
this.Lines.Clear();
}
}
public class LogLine
{
public string Message { get; set; }
public DateTime LogDate { get; set; }
public LogTypes LogType { get; set; }
public LogLine()
{
this.LogDate = DateTime.Now;
this.LogType = LogTypes.Info;
}
public override string ToString()
{
return String.Format("{0} [{1}] {2}", LogDate, LogType, Message);
}
}
public class ConsoleLogger : BaseLogger
{
/// <summary>
/// Outputs the result to the Console Window
/// </summary>
public override void Flush()
{
foreach (var log in Lines)
{
switch (log.LogType)
{
case LogTypes.Debug:
Console.ForegroundColor = ConsoleColor.White;
break;
case LogTypes.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
case LogTypes.Warning:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case LogTypes.Info:
default:
Console.ResetColor();
break;
}
Console.WriteLine(log.ToString());
Console.ResetColor();
}
Lines.Clear();
}
}
public class FileLogger : BaseLogger
{
public string FileOutputPath { get; private set; }
public FileLogger(string fileOutputPath)
{
FileOutputPath = fileOutputPath;
}
/// <summary>
/// Outputs the result to file.
/// </summary>
public override void Flush()
{
var output = new StringBuilder();
foreach (var log in Lines)
output.Append(log.ToString() + "\r\n");
using (var writer = new StreamWriter(FileOutputPath, true))
{
writer.Write(output.ToString());
}
Lines.Clear();
}
}
}
@hanssens
Copy link
Author

Note to self: I've added this sample also to my Extensions repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment