镜像控制台输出到文件

镜像控制台输出到文件

本文介绍了镜像控制台输出到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个C#控制台应用程序,有一个聪明的办法有控制台输出镜像到一个文本文件?

In a C# console application, is there a smart way to have console output mirrored to a text file?

目前,我只是路过相同的字符串既 Console.WriteLine InstanceOfStreamWriter.WriteLine 在日志的方法

Currently I am just passing the same string to both Console.WriteLine and InstanceOfStreamWriter.WriteLine in a log method.

推荐答案

这可能是某种更多的工作,但我会去倒过来。

This may be some kind of more work, but I would go the other way round.

实例化一个的TraceListener 控制台和一个用于日志文件;然后使用 Trace.Write 语句在code,而不是 Console.Write 。它变得更容易事后删除日志,或者控制台输出,或附加其他的日志机制。

Instantiate a TraceListener for the console and one for the log file; thereafter use Trace.Write statements in your code instead of Console.Write. It becomes easier afterwards to remove the log, or the console output, or to attach another logging mechanism.

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.");
}

据我记得,您可以定义应用程序配置使其能够启动或关闭日志记录的听众不接触版本。

As far as I can recall, you can define the listeners in the application configuration making it possible to activate or deactivate the logging without touching the build.

这篇关于镜像控制台输出到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 12:18