Cataster
Cataster

Reputation: 3521

why is TextWriter logging to file incomplete?

I am attempting to follow this solution here to mirror my Console output to a log file as well, however, i noticed that the output to file gets cut off, so the full console output is not completely outputted in the file. Why is that? Is TextWriter limited to certain amount of lines?

private TextWriter txtMirror = new StreamWriter("mirror.txt");

// Write text
private void Log(string strText)
{
    Console.WriteLine(strText);
    txtMirror.WriteLine(strText);
}

p.s. the reason im using this solution is because I have Console.Writeline in functions as well that i call in the main(). so if i was to use this solution instead, i would have to open a using statement everywhere i have a Console.WriteLine()...which seems redundant

Upvotes: 0

Views: 318

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

You can use the AutoFlush property System_IO_StreamWriter_Flush

Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close. Setting AutoFlush to true means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed.

By the way, if you are instantiating your logger class many times, you are going to have many StreamWriter objects. Make sure you dispose them as per documentation

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Disposing the objects, makes sure that flush is called and any buffered information is written to the underlying object.

Example:

// Write text
private void Log(string strText)
{
    Console.WriteLine(strText);
    using (StreamWriter txtMirror = new StreamWriter("mirror.txt")) {
        txtMirror.WriteLine(strText);
    }
}

Upvotes: 1

Related Questions