PROWAREtech
.NET: Copy Console Output to a Log File
How to copy the Console's output to a log file; written in C#.
The following ConsoleLogger
class makes it easy to copy all of the Console output to a log file.
ConsoleLogger
class usage:
public class Program
{
static void Main(string[] args)
{
string logFile = "application.log";
using (var consoleLogger = new ConsoleLogger(logFile))
{
Console.WriteLine("Hello, World!");
// NOTE: Even logs data input by the user
Console.ReadLine();
// NOTE: Put entire application inside this block
}
}
}
ConsoleLogger
class:
public class ConsoleLogger : IDisposable
{
private FileStream fileStream;
private StreamWriter fileWriter;
private TextWriter originalConsoleOut;
internal class MultiTextWriter : TextWriter
{
private IEnumerable<TextWriter> writers;
public MultiTextWriter(IEnumerable<TextWriter> writers)
{
this.writers = writers;
}
public override void Write(char value)
{
foreach (var writer in writers)
writer.Write(value);
}
public override void Write(string? value)
{
foreach (var writer in writers)
writer.Write(value ?? string.Empty);
}
public override void Flush()
{
foreach (var writer in writers)
writer.Flush();
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
public ConsoleLogger(string logPath)
{
// NOTE: Store the original console output
originalConsoleOut = Console.Out;
// NOTE: Create log file
fileStream = new FileStream(logPath, FileMode.Create, FileAccess.Write, FileShare.Read);
fileWriter = new StreamWriter(fileStream);
fileWriter.AutoFlush = true;
// NOTE: Redirect console output to both console and file
Console.SetOut(new MultiTextWriter(new TextWriter[] { originalConsoleOut, fileWriter }));
}
public void Dispose()
{
Console.SetOut(originalConsoleOut);
if (fileWriter != null)
{
fileWriter.Dispose();
}
if (fileStream != null)
{
fileStream.Dispose();
}
}
}
Comment