Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output console to multiple streams at once in C#?

I have a program that takes the Console output and writes it to a logfile, however it no longer shows up in the console window. Is there a way to keep it in the window but write it to the log file as well?

Update:

appLogStream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read);
TextWriter logtxtWriter = Console.Out;
logstrmWriter = new StreamWriter(appLogStream);
if(!console) Console.SetOut(logstrmWriter);
logstrmWriter.AutoFlush = true;
Console.WriteLine("Started at " + DateTime.Now);

console is a constant set in the class. It basically tells it whether it is using the console window or not (readline is not called, etc, if not in console).

So is there a way to write to both the console and the file?

like image 325
Arlen Beiler Avatar asked Dec 07 '25 13:12

Arlen Beiler


1 Answers

You could simply read that stream log it and print it out.

It depends a little on your code if you assign the output stream to the inputstream of the outfile this could be a little harder if you read the content to a buffer that should be a little easier.


About your update I would suggest that you exchange all Console with a custom logging function e.g. a instance of MyLogger (code below) . Which writes your output to the console and to your log file.

class MyLogger {
    private FileStream appLogStream;

    public MyLogger() {
        appLogStream = new FileStream(logFile, FileMode.Append, FileAccess.Write,
                                      FileShare.Read);
        appLogStream.WriteLine("Started at " + DateTime.Now);
    }

    public Write(string msg) {
        Console.Write(msg);
        appLogStream.Write(msg);
    }

    public WriteLine(string msg) {
        Console.WriteLine(msg);
        appLogStream.WriteLine(msg);
    }
}
like image 161
rekire Avatar answered Dec 10 '25 03:12

rekire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!