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

问题描述

在 C# 控制台应用程序中,是否有将控制台输出镜像到文本文件的智能方法?

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

目前我只是在日志方法中将相同的字符串传递给 Console.WriteLineInstanceOfStreamWriter.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 语句而不是 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-31 15:03