Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Created May 17, 2019 11:19
Show Gist options
  • Save DhavalDalal/da6adab863720897a2ca048aabd91bf5 to your computer and use it in GitHub Desktop.
Save DhavalDalal/da6adab863720897a2ca048aabd91bf5 to your computer and use it in GitHub Desktop.
Logger Refactoring (C#)

Logger Refactoring (C#)

using Logging;
public class Client {
public static void Main(string[] args) {
var db = new DatabaseLogger("url");
db.Log(Level.INFO, "Hello");
var console = new ConsoleLogger();
console.Log(Level.INFO, "Hello");
var file = new FileLogger(@"C:\directory\log.txt");
file.Log(Level.DEBUG, "Hello");
}
}
namespace Logging
{
public class ConsoleLogger : Logger {
public override void Write(string message) {
Console.WriteLine($"Console Logger writing => {message}");
}
}
}
namespace Logging
{
public class DatabaseLogger : Logger {
private readonly string url;
public DatabaseLogger(string url) {
this.url = url;
}
public override void Write(string message) {
Console.WriteLine($"Database Logger writing to {url} => {message}");
}
}
}
using System.IO;
namespace Logging
{
public class FileLogger : Logger {
private readonly string path;
public FileLogger(string path) {
this.path = path;
}
public override void Write(string message) {
// var text = message + Environment.NewLine;
// File.AppendAllText(path, text);
Console.WriteLine($"File Logger writing to {path} => {message}");
}
}
}
using System.Threading;
namespace Logging
{
public enum Level { DEBUG, INFO, WARN, ERROR, FATAL };
public abstract class Logger {
public void Log(Level level, string message) {
var logMessage = Enrich(level, message);
Write(logMessage);
}
// Hook
protected internal string Enrich(Level level, string message) {
return string.Format($"{DateTime.Now} [{Thread.CurrentThread}-{Thread.CurrentThread.ManagedThreadId}] {level} {message}");
}
//Mandate
public abstract void Write(string message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment