If you want to log all things written to Console.Out, you can create your own LoggingConsoleWriter that extends TextWriter and writes all text to multiple TextWriters, one of which can be a log-file. Then, you can set the standard output to an instance of this class using the Console.SetOut()-method:
// This class writes to two different outputs, one of which can be the log
public class LoggingConsoleWriter : TextWriter
{
private readonly TextWriter _output;
private readonly TextWriter _log;
public LoggingConsoleWriter(TextWriter output, TextWriter log)
{
_output = output;
_log = log;
}
public override void Write(char value)
{
_output.Write(value);
_log.Write(value);
}
public override Encoding Encoding => _output.Encoding;
}
class Program
{
static void Main(string[] args)
{
var logOutput = new StreamWriter(File.OpenWrite("log.txt"));
var newOutput = new LoggingConsoleWriter(Console.Out, logOutput);
// Redirect all Console.WriteX calls to write to newOutput
Console.SetOut(newOutput);
// This call will write to logOutput and the original Console.Out
// through the LoggingConsoleWriter
Console.WriteLine("Hello");
}
}
Alternatively, if you just want to log to a string variable. You can instantiate a StringWriter instead, like so:
class Program
{
static void Main(string[] args)
{
var sw = new StringWriter();
var newOutput = new LoggingConsoleWriter(Console.Out, logOutput);
// Redirect all Console.WriteX calls to write to newOutput
Console.SetOut(newOutput);
// This call will write to the StringWriter and the original Console.Out
// through the LoggingConsoleWriter
Console.WriteLine("Hello");
// Retrieve the currently written values
string output = sw.GetStringBuilder().ToString();
}
}
string val = "Hello"and thenConsole.WriteLine(val);Console.WriteLine()returns void (nothing). So there is no output to store.