In a C# console application, is there a smart way to have console output mirrored to a text file?
Currently I am just passing the same string to both Console.WriteLine
and InstanceOfStreamWriter.WriteLine
in a log method.
In a C# console application, is there a smart way to have console output mirrored to a text file?
Currently I am just passing the same string to both Console.WriteLine
and InstanceOfStreamWriter.WriteLine
in a log method.
Check out log4net. With log4net you can set up console and file appenders that will can output log messages to both places with a single log statement.
Log4net can do this for you. You would only write something like this:
logger.info("Message");
A configuration will determine whether the print out will go to console, file or both.
You could subclass the TextWriter class, and then assign its instance to the Console.Out using the Console.SetOut method - which in particular does the same thing as passing the same string to both methods in the log method.
Another way might declaring your own Console class and use the using statement to distinguish between the classes:
using Console = My.Very.Own.Little.Console;
To access the standard console you'd then need:
global::Console.Whatever
This may be some kind of more work, but I would go the other way round.
Instantiate a TraceListener for the console and one for the logfile. After that use Trace.Write
Statements in your code instead of Console.Write
. Like this it is easier afterwards to remove the log, or the console output, or to attach another way for logging.
static void Main(string[] args)
{
Trace.Listeners.Clear();
TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Path.GetTempPath(), AppDomain.CurrentDomain.FriendlyName));
twtl.Name = "TextLogger";
twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;
ConsoleTraceListener ctl = new ConsoleTraceListener(false);
ctl.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
Trace.WriteLine("The first line to be in the logfile and on the console.");
}
AFAIR you can define the listeners in the application configuration, so without touching the build, you can later activate/deactivate the logging.
Can't you just redirect the output to a file, using the >
command?
c:\>Console.exe > c:/temp/output.txt
If you need to mirror, you can try find a win32 version of tee
that splits the output to a file.