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.");
}
您可以使用 Log4Net 库。
它可以同时写入文件和控制台,以及任何其他地方(例如,数据库),具有灵活的设置,多线程支持。
而且您不必重新发明轮子。
你也可以这样做:
取自这里:
https://stackoverflow.com/questions/420429/mirroring-console-output-to-a-file