I've been using logging librarys recently and somebody told me to try and write my own. I've kept it minimal but the onyl drawback is I can't log in static classes, due to TClass.
Looking for constructive criticism on how to improve it, thanks.
How do I declare a logger variable?
private static readonly Logger<CatalogController> Logger = new Logger<CatalogController>();
I guess another drawback is that its pretty long, including the class name (twice) and then all the access modifiers and class names of the logger, it an get pretty ugly.
public class Logger <TClass>
{
private readonly Type _className;
public Logger()
{
_className = typeof(TClass);
}
public void Trace(string message, bool log = false)
{
Log(message, ConsoleColor.White, log);
}
public void Warn(string message, bool log = false)
{
Log(message, ConsoleColor.Yellow, log);
}
public void Debug(string message, bool log = false)
{
Log(message, ConsoleColor.Cyan, log);
}
public void Success(string message, bool log = false)
{
Log(message, ConsoleColor.Green, log);
}
public void Error(string message, bool log = false)
{
Log(message, ConsoleColor.Red, log);
}
public void Error(Exception e)
{
Log("An error occurred: " + Environment.NewLine + e, ConsoleColor.Red);
}
private void Log(string message, ConsoleColor color, bool log = false)
{
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine($"[{DateTime.Now:MM/dd HH:mm:ss}] " + message);
Console.ForegroundColor = oldColor;
string logFile;
switch (color)
{
case ConsoleColor.Yellow:
logFile = "error.log";
break;
case ConsoleColor.Cyan:
logFile = "debug.log";
break;
case ConsoleColor.Red:
logFile = "error.log";
break;
default:
logFile = "trace.log";
break;
}
LogToFile(logFile, $"Occurred at [{DateTime.Now:MM/dd HH:mm:ss}] in [{_className.FullName}]: " + message);
}
private static void LogToFile(string file, string content)
{
var executionPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var fileWriter = new StreamWriter(executionPath + "/resources/logging/" + file, true);
fileWriter.WriteLine(content);
fileWriter.Close();
}
}