Dacto Dacto - 21 days ago 4x
C# Question

Best method of logging to txt file?

What would be the best method of recording to a log(.txt) from a console program?
My program loops multiple times always outputting different data based on what the user wants, so im searching for the best, most efficient way to achieve this.

i know i can always reopen a stream and then close it, but everytime i do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again, imo that doesnt seem very resourse friendly.

using c#;
using .net2.2;

I forgot to mention that i'm using multiple threads that all have output data that i want to log,(opening/closing the same file or accessing the same file on different threads might be bad) the "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however i don't know how to do that


You could hook into the tracing framework that forms part of the CLR. Using a simple class like: http://www.chaosink.co.uk/files/tracing.zip you can selectively log diagnostic information. To use it add the class to your application. Create an inistance of the tracer in your class like:

private Tracing trace = new Tracing("My.Namespace.Class");

and call it using:

    trace.Verbose("Entered MyClass");
    int x = 12;
    trace.Information("X is: {0}", x);
    trace.Verbose("Leaving MyClass");

There are 4 levels of information in the inbuilt tracing framework:

Verbose - To log program flow

Information - To log specific information of interest to monitors

Warning - To log an invalid state or recoverable exception

Error - To log an unrecoverable exception or state

To access the information from your application then add into the app.config (or web.config) the following:

    <trace autoflush="false" indentsize="4">
    		<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\mylogfile.log" />
    	<add name="My.Namespace.Class" value="4"/>		

You can also attach listeners for publishing to the eventlog or anywhere else that interests you. More information on the tracing framework can be found at: