I need a very simple to imagine thing - modify System.Console class method WriteLine to write not only in console, but also in text log file.
I simply need to run this function with preset arguments prior to any call to WriteLine and then do generic WriteLine:
class Logger
{
static public void WriteLog(string logMessage, string fileName ,bool addTimeStamp = true)
{
//Getting temp folder
string destPath = Path.GetTempPath();
//Creating folder
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
//Naming log file
var filePath = String.Format("{0}\\{1}.log",
destPath,
fileName
);
//Writing to timestamp
if (addTimeStamp)
{
logMessage = String.Format("[{0}] - {1}{2}",
DateTime.Now.ToString("HH:mm:ss", CultureInfo.CurrentCulture),
logMessage,
Environment.NewLine);
}
else
{
logMessage = String.Format("{0}{1}",
logMessage,
Environment.NewLine);
}
//Writing to log
File.AppendAllText(filePath, logMessage);
}
}
I thought about inheritance, but I cannot even create a class since "Static class ConsoleX cannot derive from type Console. Static classes must derive from object".
Is there at all simple way to wrap around WriteLine method? I would do a separate (not inherited) class for it but then I need to create like 18 overloads for this method just to pass through arguments to 18 overloads of generic WriteLine, so it feels like waste of effort for seemingly simple thing.
Console.WriteLineis equivalent toConsole.Out.WriteLine, so you can implement your ownTextWriterand pass it toConsole.SetOutto achieve your purpose.BTW a class can not inherit a static class in any way.
BTW 2, the default console ouput is synchronized, but your method isn't, this is what you need to consider, because you may get IOException.